Nuxt v2.15.8 on Node.js 14.21.1 on Plesk Obsidian 18.0.48
I am trying to make use of environmental variables in the nodejs module of Plesk. But it seems I cannot access the variables during build.
I set up a basic nuxt project with:
npm init nuxt-app
And to be able to use it with the Plesk nodejs module I used:
npm i --save nuxt-start
If I try to access these variables in nuxt.config.js, they are undefined. If I use a .env file instead, this works.
proxy: {
'/api/': {
target: process.env.WP_BACKEND_URL || 'https://fallback.domain.tld',
},
},
Using it in publicRuntimeConfig (also in nuxt.config.js) works fine:
publicRuntimeConfig: {
wpBackendUrl: process.env.WP_BACKEND_URL || 'https://fallback.domain.tld',
},
UPDATE 1:
Ok, I did some further testing and it looks as if it is running properly. And here is what threw me off.
During build I get the following output:
> [email protected] build
> nuxt build
ℹ [HPM] Proxy created: /api/ -> https://fallback.domain.tld
ℹ [HPM] Proxy rewrite rule created: "^/api/" ~> "/wp-json/wp/v2/"
ℹ Production build
ℹ Bundling only for client side
ℹ Target: static
This shows /api/ pointing to the wrong (the fallback) url. But if I later do an axios get to this proxy, it actually points to the correct url (https://wp.domain.tld)
UPDATE 2:
Same happens here, only in this case, the URL doesn't get changed during runtime.
image: {
domains: [
process.env.WP_BACKEND_URL || 'https://fallback.domain.tld',
]
},
I think the custom environmental variables set via Plesk are not available during build time but during runtime. Which leads to the problems I am experiencing. If I use an .env file instead the environmental variables are available during build and runtime.
No idea how to fix this or work around it. So I guess I am back at using an .env file instead.
I've had a CentOS7 server with Plesk Obsidian, and my nuxt apps would build perfectly using the custom environment variables instead of a .env file.
But recently, I replaced the server with a newer one running Ubuntu 20.x, and Plesk can't seem to read by environment variables anymore, although I can't understand why :/
Adding the .env file to the app root allowed me to build without issues.
In any case, for nuxt 2 you have to use dotenv to access the environment variables.