6

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?

Sebastian
  • 1,225
  • 1
  • 16
  • 27

4 Answers4

12

I had a similar issue, I created 2 files in the root ".env.development" and ".env.production" but was still not able to access the env file variables - it was returning undefined in my gatsby-config.js file.

Got it working by npm installing dotenv and doing this:

1) When running gatsby develop process.env.NODE_ENV was returning undefined, but when running gatsby build it was returning 'production' so I define it here:

let env = process.env.NODE_ENV || 'development';

2) Then I used dotenv but specify the filepath based on the process.env.NODE_ENV

require('dotenv').config({path: `./.env.${env}`}); 

3) Then you can access your variables for your config:

module.exports = {
siteMetadata: {
    title: `Gatsby Default Starter`,
},
plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `${process.env.CONTENTFUL_ID}`,
        accessToken: `${process.env.CONTENTFUL_TOKEN}`,
        },
    },
],
}
laij84
  • 261
  • 2
  • 8
  • 1
    This does work. Why is it necessary, though? My takeaway from [the docs](https://www.gatsbyjs.org/docs/environment-variables/) was that values defined in .env.development and .env.production would be available in gatsby-config.js. – pdoherty926 Dec 17 '18 at 22:03
  • indeed. i had the same takeaway from reading the gatsby docs as pdoherty. nonetheless, your solution rocks! the env setup works fine for me now!! Thanks – Hendry Lim Mar 01 '20 at 14:47
  • I too was getting headache due to this issue. Tried above method and it worked flawlessly. – Sunny Prakash May 02 '20 at 17:43
8

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.

Kyle Mathews
  • 3,240
  • 24
  • 22
1

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);
};
odinho - Velmont
  • 20,922
  • 6
  • 41
  • 33
-1

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!
cs95
  • 379,657
  • 97
  • 704
  • 746