TABLE OF CONTENTS

How to Use Gatsby Env(ironment) Variables on Netlify Websites?

Michał Moroz
By Michał Moroz
gatsbypicturepagepro

Intro

Did you ever have to change the API URL you’re using or to set analytics keys for different environments (like production, staging, testing)? Or do you want to manage if some of the additional scripts  (like UserGuiding) should be fired only on the LIVE version of our app? What if you can do everything without any source code modifications?  That’s what environment variables can help with.

What are environment variables?

Environment Variables are good for setting application execution parameters that are used by processes over which you do not have your direct control. They are also helpful as they allow you to make changes to different environments like e.g. (test environment), change the API endpoint key.

If our application is to be deployed, for example, on Netlify, thanks to the environment variable we can change the URL of the API endpoint used by the application, or some token – without interfering with the code. 

Environment variables are an important aspect if we want to hide some API key data from the outside world. Below, I will describe how to add environment variables in Netlify + Gatsby JS and give examples of such variables.

Netlify and Gatsby environment variables

Netlify allows you to add environment variables to the build process.

By default, Gatsby supports 2 environments:

  • Development – if you run gatsby develop
  • Production –  if you run gatsby build / gatsby serve

We will go step by step on how to add an environment variable to netlify while working on Gatsby.

Two types of environment variables in Gatsby

Client-side environment variables

Client-side env variables are public API keys that we want to reuse and we don’t mind sharing them with the client. e.g:

  • url addresses
  • api address

Gatsby has security measures in place to avoid the unwanted disclosure of secrets.

Only variables prefixed with GATSBY_ will be available to the client.

So if we create a variable in the .env file named MY_VARIABLE, it will not be accessible to Gatsby.

If we change its name to GATSBY_MY_VARIABLE, we will be able to use it on the client’s side.

Server side (build-time) environment variables

There are keys that we only need during compilation, for example an API key to download content from the CMS.

We only need to make these API calls when we’re building the site (and not when the client requests the page).

Therefore, the built version of the Gatsby project does not need to access it.

How to use Gatsby environment variables on Netlify

Step 1: Creating a environment variable with Gatsby

Let’s start by creating an environmental variable. To make it easier to understand environment variables, we will not create two separate files for environment variables (development and production). We will create one file that we will use at each stage.

We need to create an .env file in the root of project

Add an example environment variable GATSBY_EXAMPLE_VAR to the .env file

The variable name should start with GATSBY_

Inside that file, let’s add:

GATSBY_EXAMPLE_VAR=”This is my development env variable.”

Example of Gatsby env variable

Step 2:  Include dotenv in gatsby-config

In the gatsby-config.js file we add the following config to allow the use of our variables from the .env file

require("dotenv").config({
 path: `.env`,
})

if you use .env.development / .env.production

require("dotenv").config({
 path: `.env.${process.env.NODE_ENV}`,
})

Step 3: Use

If we already have the GATSBY_EXAMPLE_VAR environment variable added, we can use it on our website.

Finally, to check that this works, let’s open pages/index.js and let’s change our ‘<h1>’ tag’s content.

We add an example header:

<h1>{process.env.GATSBY_EXAMPLE_VAR}</h1>

If we have a development server running, the value of our environment variable should be displayed on the main page.

Gatsby default starter - examples of a header

Make sure you have added the .env files to gitignore. There is no need to put these files in the repository

Step 4: Deploying the website to Netlify

Ok, if we are already able to use our environment variable in the local environment, we can proceed to using it in Netlify.

I assume that your website has already been implemented in Netlify.

If our website is implemented in netlify and deployed, we can log into the Netlify panel.

From the Sites section, we choose our site. Enter the Site Settings tab, and then select Build & deploy -> Environment from the side menu:

Site section of Netlify Panel

Then click the New variable button and add our variable. In the key field, we enter the name of our variable and in the value field we add the value that we want to use in the production.

After building the project on the production version of the website, we will see the header “This is my production env variable”.

Env variables – in practice

The above example of using an environmental variable is rather impractical. So I will present a few examples of the use of such a variable in a real project.

The greatest advantage of environmental variables is the use of other variables depending on the environment. Let’s assume we want to use an API which has two versions – development and production. So locally we are able to connect to the development API and in the Netlify configuration we add the production API.

Environment variable for Google keys

The most popular use of an environmental variable in a gatsby environment is certainly the use of Google Analytics and Google Tag Manager keys.

Let us assume that we are using Google Tag Manager. So we add the appropriate variable to the .env file.

Adding env variable to Google Tag Manager

Then we connect our variables to the configuration of the GTM plugin.


{
  resolve: 'gatsby-plugin-google-tagmanager',
  options: {
    id: process.env.GTM_KEY,
    includeInDevelopment: false,
    defaultDataLayer: { platform: 'gatsby' },
    routeChangeEventName: 'gatsby-route-change',
  },
},

Environment variable for GRAPHQL source

Similarly to the previous examples – we add our variable and then use it in the right place (in this case in the plugin):

adding environment variables for GraphQL
{
  resolve: 'gatsby-source-graphql',
  options: {
    typeName" 'wp',
    fieldName: 'wp',
    url: process.env.GRAPHQL_URL,
  },
},

Leave a Reply