Environment Variables
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.env.development.For builds, it will load from.env.production.
A.env file could look like:
To load these into Node.js, add the following code snippet to the top of yourgatsby-config.js file:
This loadsprocess.env.GATSBY_API_URL andprocess.env.API_KEY for use ingatsby-*.js files and functions.
For example, when configuring a plugin ingatsby-config.js:
Accessing Environment Variables in the browser.
By default, environment variables are only available in Node.js code and are not available in the browser as somevariables should be kept secret and not exposed to anyone visiting the site.
To expose a variable in the browser, you must preface its name withGATSBY_. SoGATSBY_API_URL will be available inbrowser code butAPI_KEY will not.
Variables are set when JavaScript is compiled so when the development server is startedor you build your site.
Add.env* files to .gitignore
Environment variable files should not be committed to Git as they often contain secretswhich are not safe to add to Git. Instead, add.env.* to your.gitignore file andset up the environment variables manually on Gatsby Cloud and locally.
Environment variables on Gatsby Cloud
In Gatsby Cloud you can configure environment variables in each site’s “Site Settings”. You can read more aboutmanaging environment variables in Gatsby Cloud andenvironment variables specific to Gatsby Cloud.
Additional Environments (Staging, Test, etc.)
You can create additional environments beyonddevelopment andproduction throughcustomizingdotenv’spath configuration. E.g. to add a staging environment you couldrun the Gatsby build command like:
STAGING=true gatsby build
and then in yourgatsby-config.js file:
Reserved Environment Variables:
You can not override certain environment variables that are used internally:
NODE_ENVPUBLIC_DIR
Gatsby also allows you to specify another environment variable when running thelocal development server (e.g.npm run develop):
ENABLE_GATSBY_REFRESH_ENDPOINT
This allows you to refresh your sourced content. SeeRefreshing Content.
Gatsby detects an optimal level of CPU cores to use duringgatsby build basedon the OS reported number of physical CPUs. For builds that are run in virtualenvironments, you may need to adjust the number of worker parallelism with theGATSBY_CPU_COUNT environment variable. SeeMulti-corebuilds.