Skip to content

Commit 489c578

Browse files
jongearKyleAMathews
authored andcommitted
Documentation for multiple environments (#4858)
* Documentation for multiple environments Updating documentation to provide guidance on environment support beyond development and production * add gatsby develop environment command
1 parent 2983e0f commit 489c578

File tree

1 file changed

+56
-3
lines changed

1 file changed

+56
-3
lines changed

docs/docs/environment-variables.md

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ If you want to access variables in `.env.*` files in your node.js code, use the
2323
NPM package [dotenv](https://www.npmjs.com/package/dotenv). Install the package and
2424
require it in your `gatsby-config.js` or `gatsby-node.js` the following way on top of your file:
2525

26-
```
26+
```javascript
2727
require('dotenv').config({
2828
path: `.env.${process.env.NODE_ENV}`
2929
});
@@ -33,13 +33,13 @@ Now the variables are available.
3333

3434
## Example
3535

36-
```
36+
```shell
3737
# Example .env.development file
3838

3939
API_URL=https://dev.example.com/api
4040
```
4141

42-
```
42+
```shell
4343
# Example .env.production file
4444

4545
API_URL=https://example.com/api
@@ -71,3 +71,56 @@ Reserved environment variables:
7171

7272
* `NODE_ENV`
7373
* `PUBLIC_DIR`
74+
75+
## Additional Environments (Staging, Test, etc)
76+
77+
`NODE_ENV` is a reserved environment variable in Gatsby as it is needed by the build system to make key optimizations when compiling React and other modules. For this reason it is advised to make use of a secondary environment variable for additional environment support.
78+
79+
For instance. If you would like to add a staging environment with a custom Google Analytics Tracking ID. You can add `.env.staging` at the root of your project with the following modification to your `gatsby-config.js`
80+
81+
### Example
82+
83+
```shell
84+
# .env.staging
85+
GATSBY_GA_TRACKING_ID="UA-1234567890"
86+
```
87+
88+
```javascript
89+
// gatsby-config.js
90+
91+
let activeEnv = process.env.ACTIVE_ENV;
92+
93+
if (!activeEnv) {
94+
activeEnv = 'development';
95+
}
96+
97+
require('dotenv').config({
98+
path: `.env.${activeEnv}`
99+
});
100+
101+
module.exports = {
102+
siteMetadata: {
103+
title: 'Gatsby Default Starter'
104+
},
105+
plugins: [
106+
{
107+
resolve: `gatsby-plugin-google-analytics`,
108+
options: {
109+
trackingId: process.env.GATSBY_GA_TRACKING_ID,
110+
// Puts tracking script in the head instead of the body
111+
head: false,
112+
// Setting this parameter is optional
113+
anonymize: true,
114+
// Setting this parameter is also optional
115+
respectDNT: true
116+
}
117+
}
118+
]
119+
};
120+
```
121+
122+
Local testing of staging is as simple as
123+
124+
```
125+
ACTIVE_ENV=staging gatsby develop
126+
```

0 commit comments

Comments
 (0)