justask.dev

Community powered answers to your dev questions

Environment variables in Gatsby

posted: 2020 January 22nd

category: gatsby

Edit this post on GitHub.

Back

Adding env variables and accessing them in Gatsby is easier than you think! We start in the gatsby-config.js file by creating a activeEnv check for which mode we are working in via the process.env global variable which is available via node in our Gatsby project.

We then require the dotenv library which is also available to use via node, and set the config path to the activeEnv variable.

1let activeEnv =
2 process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development" || "production"
3
4require("dotenv").config({
5 path: `.env.${activeEnv}`,
6})
7
8module.exports = {
9 ....
10}

We can then create our .env files in our projects root. You can set env variables for both development and production environments.

1.env.development
2.env.production

We now have access to our env variables in our gatsby-config.js file:

1let activeEnv =
2 process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development" || "production"
3
4require("dotenv").config({
5 path: `.env.${activeEnv}`,
6})
7
8module.exports = {
9 plugins: [
10 {
11 resolve: 'gatsby-source-something-cool',
12 options: {
13 projectId: process.env.MY_ENV_VARIABLE,
14
15 }
16 ]
17}

Author: Rich Haines