reactjsenvironment-variablesgatsbygatsby-cloud

Gatsby Cloud environment variables not working in production


In a Gatsby project hosted in Gatsby Cloud I'm passing an API key as an environment variables, but unfortunately it's not available...

The code looks like this:

import React, { useEffect, useState } from 'react';
import Airtable from 'airtable';

Airtable.configure({ apiKey: process.env.AIRTABLE_API_KEY });

const base = Airtable.base('appKjIv7utFmqAkdT');

function Gallery() {...

You can see where I'm inserting the API key.

My gatsby-config.js looks like this (I'm loading dotenv on top):

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

module.exports = {
  siteMetadata: {
    title: `wernergeller.com`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  plugins: [
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: '123',
      },
    },
    'gatsby-plugin-image',
    'gatsby-plugin-sitemap',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: './src/images/',
      },
      __key: 'images',
    },
  ],
};

Locally (gatsby develop) this is working well.

Any help is highly appreciated!


Solution

  • In Gatsby Cloud variables needs to be added in the dashboard. The URL is something like: https://www.gatsbyjs.com/dashboard/YOUR_ORGANIZATION_UUID/settings/general#env-vars

    And visually:

    enter image description here

    You can add variables individually or in a bulk with key:value pair:

    enter image description here

    Keep in mind that if you have environment variables that need to be accessed in the browser rather than the server, you'll need to prefix with GATSBY_.

    It looks that the Airtable configuration is set on the browser, so you will need to change the key to:

    Airtable.configure({ apiKey: process.env.GATSBY_AIRTABLE_API_KEY });
    

    Changing the environment variable accordingly in the process.env and in the Gatsby Cloud dashboard.

    Test your site with gatsby build locally before pushing it because gatsby develop it's not a full representation of your built/compiled project.