I set up .env file and gatsby-config.js as below.
// .env.development
GATSBY_API_URL=https://example.com/api
In Gatsby, availability of your environment variables depends on many factors:
GATSBY_
are treated differently..env.production
and .env.development
.dotenv
npm package to load the env file.Here are the different ways to make an environment variable accessible in server and browser environments. Choose whichever fits your setup best.
1. Define an OS environment variable.
MY_VAR='my value'; export MY_VAR // will persist in the OS environment
npm run start
OR
MY_VAR='my value' npm run start // will set the variable for that process only
Note: variable name doesn't matter.
2. Create an env file and define variable there.
echo MY_VAR='my value' >> .env.development
Load the file in gatsby-config.js:
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
})
Note: file name doesn't matter. Variable name doesn't matter.
1. Create a .env.development
(.env.production
for prod environment) file and define a variable there.
Note: file name does matter. Variable name doesn't matter.
2. Create an environment file named differently (say .env
) and define a GATSBY_
prefixed variable there.
echo GATSBY_MY_VAR='my value' >> .env
Load the file in gatsby-config.js
with dotenv
.
require('dotenv').config() // .env is loaded by default, no need to specify path
Note: file name does not matter. Variable name does matter.
3. Define a GATSBY_
prefixed OS environment variable.
GATSBY_MY_VAR='my value'; export GATSBY_MY_VAR
npm run start
OR
GATSBY_MY_VAR='my value' npm run start
Note: variable name does matter.