0

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!

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67

1 Answers1

1

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.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • Thanks a lot, Ferran! So I'm calling the Gatsby Cloud variable GATSBY_AIRTABLE_API_KEY as well? (so including GATSBY prefix?) – Rupert Hoffschmidt Oct 03 '22 at 13:46
  • Yes, that's the idea if you are using the variables in the browser-side. If the issue has been solved please consider accepting the answer to close the issue – Ferran Buireu Oct 03 '22 at 13:52
  • Hi @FerranBuireu! I have followed your steps, but I am still getting undefined client-side, even after defining them in Gatsby Cloud and trying with both GATSBY_ and without. It works in development but not production – j1nma Aug 05 '23 at 07:19