Nuxt dotenv options require in nuxt-config.js doesn't work

aloiseau17
0
aloiseau17
commented 6 months ago

Hi,

I tried to use nuxt-dotenv with fileaname custom options like that:

modules: [
    ['@nuxtjs/dotenv', {
      filename: '.env.dev',
  }],
  ],

It's working fine in my app but not in my nuxt-config.js
I import dotenv at the top:

require('dotenv').config()

Before that I had to add the dotenv dependency to my package.json.
But the custom .env file wasn't read. Only .env is working.

0
aloiseau17
0
aloiseau17
commented 5 months ago

Ok, I just misunderstood the way to use .env inside nuxt-config.js

I just have to configure dot-env and not nuxtjs/dotenv when I require it inside nuxt-config.js
require('dotenv').config({ path: '.env.dev' })

0
cuong-nguyen
0
cuong-nguyen
commented 22 days ago

Sorry to bring the topic up again, aloiseau17 solution works but what's the purpose of

We can override the filename when we need to use different config files for different environments.
['@nuxtjs/dotenv', { filename: '.env.prod' }]

Also with aloiseau17 solution, according to the doc

Note that this is the path to the folder where the .env file live, not to the .env file itself.

It's confusing!

0
cuong-nguyen
0
cuong-nguyen
commented 21 days ago

For those who might wonder the same thing, this is the answer from a Discord contributor

dotenv.config() merges your env variables into process env variables (process.env in node) while nuxt module also merges them to context.env.
Merging into process.env happens on running module so if you need them available earlier (for use in nuxt.config.js for example), you might want to additionally call dotenv.config() manually.
those two have different APIs regarding filename/path so follow documentation of respective module/pacakage
actually nuxt module doesn't call dotenv.config() so it won't merge your env variables to process.env the same way as dotenv would itself

0
Informations
Question โ€ข Unresolved
#c19 - Created 6 months ago