Environment Variables

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

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

I. What are environment variables?

We can use environment varaibles 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 varaibles 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 environmet 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 .gitignore file.

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