How to run Nuxt2 serverMiddleware with pm2 - vue.js

I have a simple Nuxt ssr app with a serverMidlleware handling one api endpoint (/api/contact). To deploy the app I am using pm2.
Running the app in development and in production (locally without pm2) everything works fine. Deploying it on a basic ubuntu server using pm2, the api endpoint becomes unreachable (404 not found).
As pointed out here, the middleware is not included in the .nuxt build. So, I made sure to copy the api directory (where my middleware is located) too.
for pm2 deployment, ecosystem.config.js:
module.exports = {
apps: [
{
name: 'App',
exec_mode: 'cluster',
instances: 'max',
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start'
}
]
}
and inside nuxt.config.js:
serverMiddleware: [
{ path: '/api/contact', handler: '~/api/contact.js' }
]
As only the deployment via pm2 fails, I assume the other files are not of interest. I am assuming this must be related to some sort of pm2 config to find the api folder.

Following my answer here solved the issue here too.
You probably had something missing in your nuxt.config.js file
export default {
ssr: true,
target: 'server',
modules: [
'#nuxtjs/axios',
],
serverMiddleware: [
{ path: '/api', handler: '~/server-middleware/rest.js' },
],
}

Related

Use express.js as middleware for nuxtjs?

I've been following this tutorial that explains how to have an express app in your nuxtjs app, but when I make a postman request to the route defined in the express app, it returns 404 error. Is this tutorial outdated?
Here's my nuxt.config.js:
import { resolve } from 'path'
export default {
ssr: true,
target: 'server',
modules: [
'#nuxtjs/axios'
],
serverMiddleware: [
{ path: '/api', handler: '~/api/index.js' },
],
}
I made an api folder with an api folder with a index.js file in it where you can find a normal express app, I configured my nuxt.config.js file but it seems like the express.js is not running when I run the nuxtjs app. What should I do?

Why nuxt.config.js build.babel is ignored on app start, but work on app update?

My nuxt.config.js file has the following section
build: {
babel: {
presets (_, [_1, _2]) {
return [['#babel/preset-env', {}]]
},
plugins: [
['#babel/plugin-transform-runtime',
{
regenerator: true
}]
]
}
}
If I start my app (yarn dev), this section is ignored, and I've got regeneratorRuntime is not defined error instead of backend answer when I call my REST API (server middleware). But if after that (while server is up and running) I perform some changes in nuxt.config.js (i.e. set regenerator to false and then again to true), app is beeing regenerated and my REST API starts working fine.
yarn generate fails with ERROR ServerMiddleware Error: regeneratorRuntime is not defined
How to make it working always?

vuejs pwa prevent using cache when requesting /api/ routes

i had created a Vuejs project with PWA support but when i am building its production build it always using cached version of api requests i want to prevent it from using cache for api requests or change its policy from being to cacheFirst to NetworkFirst for api i found a i had changed vue.config.js to prevent cacheing but its not working
pwa: {
workboxOptions: {
exclude: [/.*\/api\//,],
},
},
any help on how i can either prevent cache on api routes or set networkFirst policy
exclude option only works for excluding precaching assets, which is what vue generates at build time, not api requests at run time.
It seems the Cache-Control problem of the api server, but if you do not have access to that server, you can config NetworkFirst policy runtimeCaching:
module.exports = {
pwa: {
workboxOptions: {
runtimeCaching: [{
urlPattern: new RegExp('^https://api.example.com/path'),
handler: 'NetworkFirst',
}]
}
}
};

Nuxt static generated page and axios post

I have a Nuxt project. Everything is OK when I generate a static page.
However, I need to send a POST request to the other server.
I tried to use both a proxy in nuxt.config.js and just direct query, but after deploy to the ngnix eventually, nothing works.
Please help.
UPDATE. Steps to reproduce.
Create Nuxt App including axios and proxy
Configure your proxy for other webservice:
proxy: {
'/api': {
target: 'http://example.com:9000',
pathRewrite: {
'^/api': '/',
},
},
changeOrigin: true,
},
call this service somewhere in the code:
const result = await this.$axios.post('/api/email/subscribe', {email: email})
run "yarn dev" and test the service. It works locally properly.
run 'nuxt generate' and deploy the static code hosting service, for example, hosting.com
run your page which calls the above-mentioned service.
As a result, instead of making POST call to the hosting.com/api/email/subscribe, it calls localhost:3000/api/email/subscribe.
Be sure to install the nuxt versions of axios and proxy in your project #nuxt/axios and #nuxtjs/proxy
after that in your nuxt.config.js add axios as module plus this options for axios and proxy:
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
//more modules if you need
],
/*
** Axios module configuration
*/
axios: {
proxy: true,
// See https://github.com/nuxt-community/axios-module#options
},
proxy: {
'/api/': {
target: process.env.AXIOS_SERVER, // I use .env files for the variables
pathRewrite: { '^/api/': '' }, //this should be your bug
},
},
now you can use axios in any part of the code like this
const result = await this.$axios.post('/api/email/subscribe', {email: email})
it will internally resolve to AXIOS_SERVER/email/subscribe without cause cors issues.
EXTRA: test enviroments in local using multiples .env files
you can configure .env for dev and .env.prod for production, after that in local you can use yarn build && yarn start for test your app with your production enviroment. You only need add this at the top of your nuxt.config.js file
const fs = require('fs')
const path = require('path')
if (process.env.NODE_ENV === 'production' && fs.existsSync('.env.prod')) {
require('dotenv').config({ path: path.join(__dirname, `.env.prod`) })
} else {
require('dotenv').config()
}
By definition on the Nuxt docs page what nuxt generate does is: Build the application and generate every route as a HTML file (used for static hosting).
Therefore, using proxy is out of question here. Take note that you path is not even being rewritten.
And probably the result you're looking for is not hosting.com/api/email/subscribe (wit /api), but hosting.com/email/subscribe.
Nevertheless, if you use nginx then I don't think you should use Nuxt's proxy option. Nginx is built just for that so point your API calls there and in nginx config file just declare where it should point further.

Type Error global.XMLHttpRequest is not a constructor in NUXT

I am trying to use THIS library on the client side as a plugin When I npm run dev the client, I get this error
My vue2socketcluster.js file inside the plugins folder looks like this
import Vue2Socketcluster from 'vue2-socketcluster'
Vue.use(Vue2Socketcluster,{
hostname:"localhost",
secure:true,
propName:"socket" // Defaults to socket - so if you want vm.$soc you would change this to "soc"
})
and nuxt config had an entry for plugins
plugins: [
'~/plugins/vue2socketcluster'
],
Any direction will be super appreciated
Fixed it by setting server side rendering to false. Thank you
plugins: [
{ src: '~/plugins/sc', mode: 'client' }
],