Setting environment variables in Gatsby

Viewed 8218

I used this tutorial: https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/environment-variables.md

Steps I followed:

1) install dotenv@4.0.0

2) Create two files in root folder: ".env.development" and ".env.production"

3) "follow their setup instructions" (example on dotenv npm docs)

In gatsby-config.js:

const fs = require('fs');
const dotenv = require('dotenv');
const envConfig = 
dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`));
for (var k in envConfig) {
  process.env[k] = envConfig[k];
}

Unfortunately, when i run gatsby develop, NODE_ENV isn't set yet:

error Could not load gatsby-config


  Error: ENOENT: no such file or directory, open 'E:\Front-End Projects\Gatsby\sebhewelt.com\.env.undefined'

It works when I set it manually:

dotenv.parse(fs.readFileSync(`.env.development`));

I need environment variables in gatsby-config because I put sensitive data in this file:

  {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: envConfig.CONTENTFUL_SPACE_ID,
        accessToken: envConfig.CONTENTFUL_ACCESS_TOKEN
      }
    }

How to make it work?

PS: Additional question - As this made me think, I know I shouldn't put passwords and tokens on github, but as netlify builds from github, is there other safe way?

4 Answers

You should only use env files when you're comfortable checking those into git. For passwords/tokens/etc. add them to Netlify or whatever build tool you use through their dashboard.

These you can access in gatsby-config.js & gatsby-node.js via process.env.ENV_VARIABLE.

You can't access environment variables added this way in the browser however. For this you'll need to use .env.development & .env.production.

I really dislike the .env.production file pattern, our build system sets up and uses env variables and having extra build steps to write those into a file is weird. But Gatsby only whitelists GATSBY_ of the env vars, with no obvious way of adding your own.

But doing that isn't so hard, you can do it by adding something like this in the gatsby-node.js file:

exports.onCreateWebpackConfig = ({ actions, getConfig }) => {
    const config = getConfig();

    // Allow process.env.MY_WHITELIST_PREFIX_* environment variables
    const definePlugin = config.plugins.find(p => p.definitions);
    for (const [k, v] of Object.entries(process.env)) {
        if (k.startsWith("MY_WHITELIST_PREFIX_")) {
            definePlugin.definitions[`process.env.${k}`] = JSON.stringify(v);
        }
    }

    actions.replaceWebpackConfig(config);
};

After doing a few searches, I found that we can set environment variables through netlify website, here are the steps:

  1. Under your own netlify console platform, please go to settings
  2. Choose build & deploy tab (can be found on sidebar)
  3. Choose environment sub-tab option
  4. Click edit variables and add/put your credentials in
  5. Done!
Related