DEV Community

Kapil Gorve
Kapil Gorve

Posted on • Originally published at jskap.com on

GatsbyJs - Add environment variables

Development Environment

  • Create a new file named as .env.development at the root of your project.
  • Add your variable to the newly created file. Example - TEST_KEY=123
  • Change your npm run develop command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=development && gatsby develop"

For Linux -

    "develop": "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
  • Change your npm run build command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=production && gatsby develop"

For Linux -

    "build": "GATSBY_ENV=production gatsby build",

This is only if you want to build on local.

If you are using any providers like Netlify use the Linux version. You will also need to add environment variables in the service provider.

For Netlify it is in Site Settings > Build&Deploy > Environment

This post was originally published at https://www.jskap.com/blog/gatsby-add-environment-variables/

šŸ‘‹ Hi! Iā€™m Kapil. I am always chatty about building things, sharing my learnings, freelancing. Come say hi to me at https://twitter.com/kapilgorve

Top comments (3)

Collapse
 
lucaszapico profile image
LucasZapico

Hey, please double check before you post. This is incorrect and misleading, please correct or take it down as it just muddies the water for people. There is no GATSBY_ENV that overrides the environments set in gatsby develop and gatsby build. gatsby build sets the NODE_ENV to production internally and gatsby develop sets NODE_ENV to development. If you test something like "develop:bang": "set GATSBY_ENV=bang && gatsby develop" print or console.log the env variables you would see that the command you call aren't doing anything.

Collapse
 
andybrownlie profile image
thunk

Hi Kapil

Thanks for this, sort of got this working on Windows with an env variable. However, when I try to use this env variable in my gatsby-config.js to set a value with my plugins (e.g. Google Analytics tracking ID) it doesn't work. Have you managed to get it working in this gatsby-config.js file?

Collapse
 
raevilman profile image
RD

Hi Andy,

I solved it by adding below to my gatsby-config.js

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})
Enter fullscreen mode Exit fullscreen mode

Wrote a note about it at therdnotes.com/building-a-markdown...

HIH āœŒ