Home > Mobile >  Nuxt, doesnt load NUXT_ENV var
Nuxt, doesnt load NUXT_ENV var

Time:08-26

Hello I have an env var like the following in the nuxt.config.js

env: {
   BAR: process.env.BAR
}

The problem is that I need to load from os env var instead of .env file so I tried to use NUXT_ENV_ like this:

I load the env var with

export NUXT_ENV_BAR='value'

1 Try

env: {
   BAR: process.env.NUXT_ENV_BAR
}
....
console.log(process.env.BAR)
....

2 Try

....
env: {
   NUXT_ENVBAR: process.env.NUXT_ENV_BAR
}
console.log(process.env.NUXT_ENVBAR)
....

I tried the same with publicRuntimeConfig instead of env, but didn't work too.

How can I set os env var inside nuxt.js app?

Thanks

CodePudding user response:

When you set an object in JSON the format is key : value. You can not use =.

So your code should be:

env: {
   BAR: process.env.BAR
}

To manage your custom Nuxt env you can use https://github.com/nuxt-community/dotenv-module dotenv module or publicRuntimeConfig as you said.

If you want to use the 'publicRuntimeConfig' attribute in your nuxt.config.js file just implement this code:

 publicRuntimeConfig: {
   BAR: 'yourValue',
 }

Then you can access this config data with $config as $config.BAR. (To test your config in your browser just write __NUXT__.config in the console tab)

CodePudding user response:

You could create a file e.g. serverVariables.js with the server variables that you want to define at the location of your choice in your project.

export default {
  BAR: process.env.BAR || '<your default value>',
};

Next, inside your nuxt.config.js, you could import those variables at the very top like;

import serverVariables from '~/serverVariables';

Next you could map those variables to your publicRuntimeConfig like;

publicRuntimeConfig: {
    BAR: serverVariables.BAR,
}

You could then access it anywhere in your components like;

$config.BAR
  • Related