0

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

Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84

2 Answers2

1

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)

thebyteland
  • 359
  • 1
  • 2
  • 10
  • The questios is that In `your value` I need to read NUXT_ENV var, because I cannot read from a .env file i need read from os env var, and that is not working, so how can I do to work with that? – Tlaloc-ES Aug 26 '22 at 13:08
  • Have you read the dotenv module doc you have in the link? It allows you to set .env files and read them into your nuxt config. Then map your variables as you want like my example. – thebyteland Aug 26 '22 at 16:03
  • Finnaly was docker error. – Tlaloc-ES Aug 26 '22 at 16:06
0

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
aghashamim
  • 553
  • 3
  • 9