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

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?

Related

How to run Nuxt2 serverMiddleware with pm2

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' },
],
}

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.

How to implement background sync with nuxtjs/pwa?

I am trying to use workbox background-sync in Nuxtjs via #nuxt/pwa-module.
this is my workbox property in nuxt.config.js file:
workbox: {
importScripts : [
'sw-background-sync.js'
]
}
contents of plugins/sw-background-sync.js file :
console.log("backsync called")
workbox.routing.registerRoute(
'https:\/\/example.com\/api\/Survey\/post.*',
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.Plugin('myQueueName', {
maxRetentionTime: 24 * 60
})
]
}),
'POST'
);
Offline caching is supposed to work by default and it is working fine. but when I uncomment importScripts and refresh the page I get this error in console :
backsync called
workbox-sw.js:1 Uncaught Error: Config must be set before accessing workbox.* modules
at Proxy.setConfig (workbox-sw.js:1)
at sw.js:8
Any example of how to implement pwa background sync with nuxtjs would be appreciated.
Thank you very much.
Actually I should put the script inside workboxExtensions property in nuxt.config.js file:
workbox: {
workboxExtensions : '#/plugins/sw-background-sync.js'
}
When using workbox you can also put:
strategyPlugins:[{
use:'BackgroundSync',
config: {}
}],
I am still trying to find out what config to put in there.

Nuxt ignoring babel on build process

https://nuxtjs.org/api/configuration-build#babel
I originally left the presets as default.
I then followed the suggestions on
https://github.com/nuxt/nuxt.js/issues/1776
However this dealt more with pipelines
I am just trying to get it to convert the es6 to es5 (import chief among the reasons)
I get the same result or a complete failure no matter if i add the .babelrc, adjust package.json, adjust nuxt.config.js or a combination of them.
currently i have adjusted my nuxt.config.js to:
/*
** Build configuration
*/
build: {
babel: {
presets: ['#babel/preset-env'],
configFile: false,
babelrc: false,
plugins: ['#babel/plugin-syntax-dynamic-import']
}
}
When i upload the entire .nuxt folder to my server (running plesk using phusion passenger)
I get the following error
/var/www/vhosts/website.com/app/client/server.js:1
(function (exports, require, module, __filename, __dirname) { import { stringify } from 'querystring'
My site root is
/var/www/vhosts/website.com/app/client/
The first line of server.js
import { stringify } from 'querystring
Changing this to
var stringify = require("querystring").stringify
Eliminates the error however i would need to go through page after page to remove this. My understanding is i can progamically adjust this using babel. But no matter what ive tried the file stays the same.
I did use the Nuxt CLI to automatically set up babel and webpack but using the above build config is not the default. I have attempted to play with it but i get the same result
I added babel/polyfill to try and get around the import issues without any success