How to access environment variables in a react component?

Hey there, I’m new to Gatsby and I’m creating a site with a google maps component that requires the google api key. I’m not able to access this key from the component (process.env.GOOGLE_API_KEY = undefined) however, even though I created an environment variable through the Netlify UI .

Am I missing something?


This article is almost certainly the answer to your question:

If not, could you tell us more about how you are trying to use that value? That javascript looks fine, assuming that:

  1. you have that variable set during build
  2. that code RUNS during build (not, say, at browse time - where that is just a string, or anyway the environment variable isn’t set anymore) and interpolates its output into your static files.

Gatsby requirement

I also Answered this question on StackOverflow for the quick answer:

Environment variables need to start with GATSBY_ in the client-side javascript as shown in the docs.

Use GATSBY_GOOGLE_API_KEY and process.env.GATSBY_GOOGLE_API_KEY for them to be accessed during the build and bundled into your Gatsby client code.

1 Like