Setting environment variables in Gatsby

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?

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.

Managing Environment Variables, Gatsby and environment variables; Netlify and environment variables; Step Step 2 Duration: 3:19 Posted: Apr 28, 2020 After doing a few searches, I found that we can set environment variables through netlify website, here are the steps: Under your own netlify console platform, please go to settings Choose build & deploy tab (can be found on sidebar) Choose environment sub-tab option Click edit variables and add/put

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}`,
        },
    },
],
}

What Are Environment Variables and How Can I Use Them with , Change your npm run develop command to set environment. For Windows -. " develop": "set GATSBY_ENV=development && gatsby develop". Restart your dev environment. So Gatsby will load your new env file. You should be able to access your env variables using process.env.TEST_KEY in any js file. Production Environment. Create a new file named as .env.production at the root of your project. Add your variable to the newly created file. Example - TEST_KEY=123

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!

GatsbyJs - Add environment variables - DEV, You can go around it with setting the environment in develop command with NODE_ENV=development gatsby develop . Now it works as I expect,� If the characters are the "who," then the setting is the "where" and "when." This "where and when" can be very general - for example, "20th century Earth." Alternately, the setting can be each of the many different places where any of the novel’s actions occur, no matter how small.

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);
};

Environment Variables in gatsby-config.js not working � Issue #3896 , But realized that on gatsby build the env variables I set, are undefined later. The docs are specified with gatsby develop . Setting env vars on� Under the Environment Variables window, choose or highlight the PATH variable in the System Variables section shown in the window. After highlighting the PATH variable from System Variables click the Edit button. You can add or modify the path lines with the directories you want your computer to look in for executable files.

Env variables on gatsby build � Gatsby.js, 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� Learn about environment variables and how to add them to a Gatsby and Netlify project. We'll walk through a basic Gatsby starter and deploy it to Netlify with an example environment variable. ️

Setting environment variables in Gatsby, env files or the repo. Q4) I'd say that committing and deploying are generally different. Unless you have a setup with auto deployments on commit. I have added my� Gatsby uses both dotenv and webpack 's DefinePlugin to manage environment variables. By default, Gatsby supports a development and a production environment, so environment variables should be added to either a.env.development or a.env.production file. Gatsby does not support.env files that do not contain a suffix.

How are Environment Variables used with Gatsby?, Learn about environment variables and how to add them to a Gatsby and Netlify Set Future Duration: 3:19 Posted: Apr 28, 2020 Gatsby has a requirement to start your environment variables with GATSBY_ for them to be used in your client javascript. (exception NODE_ENV). (exception NODE_ENV). This follows the same pattern as a create-react-app.

Comments
  • This does work. Why is it necessary, though? My takeaway from the docs was that values defined in .env.development and .env.production would be available in gatsby-config.js.
  • 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
  • I too was getting headache due to this issue. Tried above method and it worked flawlessly.