It’s a best practice not to commit environment configuration files to source control providers unless there is absolute certainty no sensitive credentials are contained inside.
Many Gatsby developers utilize local environment configuration files to manage that sensitive information outside of source control, while simultaneously providing environment variables to continuous deployment (CD) providers in the infrastructure provider’s own interface.
To illustrate this, consider an example in which you need to consume two different versions of an API as a data source, one that exposes “development” data and the other exposing “production” data. Your environment configuration files might contain an API access token shared across both API environments, but the APIs are referred to distinctly:
# .env.development
API_ACCESS_TOKEN=da62e848ded24f69b246312456b55a66
# .env.production
API_ACCESS_TOKEN=da62e848ded24f69b246312456b55a66
When you need to refer to the API URL again in your code anywhere in your Gatsby site, including in Gatsby pages and components, you can do so as follows:
// src/pages/index.js
<
img
src
=
{
`
${
process
.
env
.
GATSBY_BASE_URL
}
/hero.jpg`
}
alt
=
"Hero image"
/>
WARNING
There are certain reserved environment variables that Gatsby does not permit you to override, as they’re used internally to optimize Gatsby builds: attempting to set NODE_ENV
or PUBLIC_DIR
yourself will result in errors.
Any environment variable prefixed with GATSBY_
will automatically be embedded as process.env.GATSBY\_\*
in compiled JavaScript, which means that the variable will be available within the context of the browser without being unintentionally exposed elsewhere. For all other environment variables without the GATSBY_
prefix, your Gatsby site can access values such as API_ACCESS_TOKEN
on the server side (i.e., Node.js) via the process.env
variable, just as when configuring source plugin options:
// gatsby-config.js
plugins
:
[
{
resolve
:
`gatsby-source-contentful`
,
options
:
{
spaceId
:
`mySpaceId`
,
accessToken
:
process
.
env
.
CONTENTFUL_ACCESS_TOKEN
,
},
},
],
NOTE
An environment variable named ENABLE_GATSBY_REFRESH_ENDPOINT
is commonly used by Gatsby developers to permit sourced data to be refreshed from an external source while running the Gatsby local development server (gatsby develop
). More information can be found in the Gatsby documentation’s guide to refreshing content. In addition, Gatsby makes available build variables (e.g., CI=true
) for more advanced CD configuration.
Leave a Reply