Ayeye Brazo
Ayeye Brazo

Reputation: 3476

System environment variables ignored by Nuxt

My Nuxt project uses system environment variables to set client ids, secrets, urls, etc...

An example is in my nuxt.config.js where I set several properties with the following formula:

{
  something: process.env.SOMETHING || 'something_for_dev'
}

Nuxt dev version is working fine because looks after the process.env.SOMETHING and correctly use something_for_dev.

Nuxt on staging has its own configuration on Azure and the SOMETHING env var is correctly set but suddenly it still continue using something_for_dev...

What should I do to let Nuxt use the sys env vars I set on my Server rather than the default used for dev? Thanks

Upvotes: 2

Views: 1142

Answers (2)

ponnex
ponnex

Reputation: 848

In addition to Aldarund comment above you could build a proper env variables in nuxt by following:

Use cross-env: npm install cross-env

In your project add a folder named environment and under the folder you could have different environment (e.g. development, staging, production)

environment folder

Your environment configs will have your baseUrl and other configs, let's say for development you could have your localhost then for the staging or production you could have your API_URL

defaults.json \\development development config

defaults.prod.json \\production production config

In nuxt.config.ts build > extend configure your different environment

nuxt.config.ts build extend envi

This will replace defaults.json depending on which environment we will run our script in package.json.

In package.json configure your script to what environment will be run (e.g npm run start will use NODE_ENV=development which will use the defaults.json with baseUrl: http://localhost:3000 and npm run build will use defaults.prod.json with baseUrl: http://www.API_URL.com and other configs

package.json cross env config

For more detail you could see cross-env

Upvotes: 0

Aldarund
Aldarund

Reputation: 17621

Env variables are set build time, not runtime. So it will be the env variables that set during your build, which seems you do on your dev machine.

So you can either build with proper env variables or use nuxt-env module, which allows runtime variables, but keep in mind that it wont allow webpack to optimize dead code and environment variables used in nuxt-env are exposed client side, so if you store secrets use the secret config option

Upvotes: 1

Related Questions