Skip to content

Commit ff86028

Browse files
authored
Documentation for multiple environments
Updating documentation to provide guidance on environment support beyond development and production
1 parent 362f78a commit ff86028

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

docs/docs/environment-variables.md

Lines changed: 51 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,51 @@ 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+
```shell
82+
# .env.staging
83+
GATSBY_GA_TRACKING_ID="UA-1234567890"
84+
```
85+
86+
```javascript
87+
// gatsby-config.js
88+
89+
let activeEnv = process.env.ACTIVE_ENV;
90+
91+
if (!activeEnv) {
92+
activeEnv = 'development';
93+
}
94+
95+
require('dotenv').config({
96+
path: `.env.${activeEnv}`
97+
});
98+
99+
module.exports = {
100+
siteMetadata: {
101+
title: 'Gatsby Default Starter'
102+
},
103+
plugins: [
104+
{
105+
resolve: `gatsby-plugin-google-analytics`,
106+
options: {
107+
trackingId: process.env.GATSBY_GA_TRACKING_ID,
108+
// Puts tracking script in the head instead of the body
109+
head: false,
110+
// Setting this parameter is optional
111+
anonymize: true,
112+
// Setting this parameter is also optional
113+
respectDNT: true
114+
}
115+
}
116+
]
117+
};
118+
119+
120+
```
121+

0 commit comments

Comments
 (0)