Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby, Environment variables not accessible in browser

I want to use environment variables. I created .env.development file and I put some variables. Then I include the dotenv plugin to read the variables in gatsby-config.js:

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

The content of my .env.development:

GATSBY_APP=MYAPP

It's working in gatbsy-node.js but in browser (REACT) it's empty. I display console.log(process.env) and it return empty object.

Even if I install and configure gatsby-plugin-env-variables.

like image 448
Youssef Lahssini Avatar asked Mar 04 '23 06:03

Youssef Lahssini


1 Answers

It looks like you're combining two approaches, and that might be where you're running into trouble.

  1. Gatsby comes out-of-the-box with support for defining environment variables in environment-specific .env.[environment] files (e.g. .env.development), provided these files are in the root of your project (i.e. your-project/.env.development). Documentation for this feature. You do not need to install or configure dotenv for this to work.

  2. Another approach is to use dotenv, which will allows you to use a general .env file. You need to then import and configure the tool, which is generally done at the very top line of gatsby-config.js and looks like this:

     require("dotenv").config()
    

Note that you do not specify the environment name (e.g. development) in this scenario, and you would not commit the .env file to your repository.

The other issue you might run into is that part of your code runs server-side, using Node, and part runs client-side (in the browser). Since process.env is only available in Node, Gatsby does some additional work to make it available in the browser. We don't want all of these variables, which frequently hold secrets, to be provided to the browser, though, so Gatsby only copies over those that whose names begin with GATSBY_. Finally, as a side effect of the way that these variables get copied over, you must explicitly reference them for your build to work:

// this is okay everywhere
const GATSBY_APP = process.env.GATSBY_APP

// this won't work in code that runs client-side, but will work
// in `gatsby-node.js` and other files that only run in Node
const { GATSBY_APP } = process.env
like image 149
coreyward Avatar answered Mar 12 '23 02:03

coreyward