Gatsby has built-in support for loading environment variables into the browser and Functions. Loading environment variables into Node.js requires a small code snippet.
In development, Gatsby will load environment variables from a file named
For builds, it will load from
.env file could look like:
To load these into Node.js, add the following code snippet to the top of your
process.env.API_KEY for use in
gatsby-*.js files and functions.
For example, when configuring a plugin in
By default, environment variables are only available in Node.js code and are not available in the browser as some variables should be kept secret and not exposed to anyone visiting the site.
To expose a variable in the browser, you must preface its name with
GATSBY_API_URL will be available in
browser code but
API_KEY will not.
Environment variable files should not be committed to Git as they often contain secrets
which are not safe to add to Git. Instead, add
.env.* to your
.gitignore file and
set up the environment variables manually on Gatsby Cloud and locally.
In Gatsby Cloud you can configure environment variables in each site’s “Site Settings”.
You can create additional environments beyond
path configuration. E.g. to add a staging environment you could
run the Gatsby build command like:
STAGING=true gatsby build
and then in your
You can not override certain environment variables that are used internally:
Gatsby also allows you to specify another environment variable when running the
local development server (e.g.
npm run develop):
This allows you to refresh your sourced content. See Refreshing Content.
Gatsby detects an optimal level of CPU cores to use during
gatsby build based
on the OS reported number of physical CPUs. For builds that are run in virtual
environments, you may need to adjust the number of worker parallelism with the
GATSBY_CPU_COUNT environment variable. See Multi-core