[Support Guide] Using environment variables on Netlify correctly

I answered using .env on Netlify to be able to use dotenv on your build on SO, but here is the cross post:

WARNING: If this is a secret key, you will not want to expose this environment variable value in any bundle that gets returned to the client. It should only be used by your build scripts to be used to create your content during build.

Issue

dotenv-webpack expects there to be a .env file to load in your variables during the webpack build of your bundle. When the repository is checked out by Netlify, the .env does not exist because for good reason it is in .gitignore.

Solution

Store your API_KEY in the Netlify build environment variables and build the .env using a script prior to running the build command.

scripts/create-env.js

const fs = require('fs')
fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}\n`)

Run the script as part of your build

node ./scripts/create-env.js && <your_existing_webpack_build_command>

Caveats & Recommendations

  • Do not use this method with a public facing repository if you are trying to hide the keys [open] because any PR or branch deploy could create a simple script into your code to expose the API_KEY
  • Only use the private keys for your build env. Public environment variables are safe to access inside your client code bundles.
  • The example script above is for simplicity so, make any script you use be able to error out with a code other than 0 so if the script fails the deploy will fail.
7 Likes