Search code examples
node.jswebpacknetlifydotenv

How can I make Netlify create a .env file during build? Or how can I make dotenv pick up system variables?


I have the following working okay locally:

// .env
MY_ENV='test'
MY_URL='http://192.168.0.16'
// webpack config
...
plugins: [
  new webpack.DefinePlugin({
    'process.env': JSON.stringify(dotenv.config().parsed)
  })
]

But when I try using MY_ENV and MY_URL with Netlify, they're undefined. I already set them up on the "Environments" tab in Netlify's dashboard.

I suspect dotenv looks for a .env file, but not system variables.

I know the plugin dotenv-webpack allows you to use system variables, but dotenv-webpack is a no-no since I need those variables to be used in the browser (they're not really secrets).

Is there any way I can make Netlify create a .env locally, so dotenv can pick it up? Or is there any way I can make dotenv use system variables?

Thanks!


Solution

  • Simply use to access the env variables

    process.env.MY_ENV
    process.env.MY_URL
    

    Don't override your process.env

    const myenv = dotenv.config().parsed;
    
    plugins: [
      new webpack.DefinePlugin({
        MY_ENV: myenv.MY_ENV || process.env.MY_ENV,
        MY_URL: myenv.MY_ENV || process.env.MY_ENV,
      })
    ]