My blog

The World is too big and beautiful to stay in one place forever!

How to use the .env file in Gatsby

Recently I started to work on a project using React/Gatsby. When I was building a contact form using Firebase, I got the following error:

NOT_FOUND: The project undefined does not exist or it does not contain an active Cloud Datastore or Cloud Firestore database. Please visit http://console.cloud.google.com to create a project or https://console.cloud.google.com/datastore/setup?project=undefined to add a Cloud Datastore or Cloud Firestore database. Note that Cloud Datastore or Cloud Firestore always have an associated App Engine app and this app must not be disabled. This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

I spent 3 days trying to figure out why I can’t insert data in DB ( Firestore ). Thanks my colleague I could fix the error. It comes out that environment variables that you defined in the .env file will not be immediately available in your Node.js scripts. To use those variables, you have to use npm package dotenv to examine the active .env.* file and attach those values. Add it by running a command:

yarn add dotenv

Then you will see gatsby-config.js in your project’s root directory. Modify your gatsby-config.js by writing in the begging of it:

let activeEnv =
    process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV || "development"
require('dotenv').config({
  path: `.env.${activeEnv}`,
})

Then rename your .env file to .env.development if you are  ‘development’ environment. You can check the documentation here.

Hope it will help you to save your time.

Naika

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top