Environment Variables

When using 3rd party services to our application or website, we should mask the Key with environmental variables.

In this article, we’ll see how to add environmental variables with Gatsby and Netlify.

I. What are environment variables?

We can use environment variables to store values provided by 3rd party services—for example, a secret key for an API request.

II. How to add environment variables in Gatsby?

In development, environment variables are loaded from .env.development.. For builds, they are loaded from .env.production..

To load these into Node.js, we add this snippet to the top of our gatsby-config.js file:

// gatsby-config.js

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

III. How to access environment variables?

For example, inside .env.development and .env.production., we add

// Inside .env file
GATSBY_API_URL=https://example.com/api

Then, we can use it in our component or page.

const searchImage = async (e) => {
e.preventDefault();
    try {
      const res = await fetch(${process.env.GATSBY_API_URL});
      const data = await res.json();
    } catch (err) {
      console.error(err);
    }
};

IV. How to keep environment variables secure?

The easiest way is to add the environment files to the .gitignore file.

We add .env.* to the .gitignore file and then set up the environment variables manually on Netlify (or other services).