Can't access gatsby environment variables on the client side

A few steps & notes that should solve your problem:

console.log(process.env) will always print empty object

To see if it's really working, you should print the variables directly, e.g. console.log(process.env.API_URL).

Make sure .env.* is in your root folder

In other words, your folder hierarchy should look something like:

.env.development
.env.production
src/
  pages/
    index.js

You don't need to prefix with GATSBY_ if you want to access env variables server-side

From the docs:

In addition to these Project Environment Variables defined in .env.* files, you could also define OS Env Vars. OS Env Vars which are prefixed with GATSBY_ will become available in browser JavaScript.

You need the GATSBY_* prefix if you are using them browser-side

The prefixing is only if you use the OS Env Vars approach (i.e. you set them directly on your server and not in these .env files).

Kill and restart gatsby develop when you've added the .env file(s)

I ran into this when reproducing on CodeSandbox (in CodeSandbox, you do the restart by going to Server Control Panel on the left, and clicking Restart Sandbox).

Here's the working example: https://codesandbox.io/s/jj8xzn2y15


Maybe worth noting that it's easy to misname the file if you are used to writing .dev or .develop.

Gatsby requires that the file is named exactly: .env.development


Make sure you've included

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

in your gatsby-config.js file before you start using your ENV variables.