Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variables in Gatsby

I used this tutorial: https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/environment-variables.md

Steps I followed:

1) install [email protected]

2) Create two files in root folder: ".env.development" and ".env.production"

3) "follow their setup instructions" (example on dotenv npm docs)

In gatsby-config.js:

const fs = require('fs');
const dotenv = require('dotenv');
const envConfig = 
dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`));
for (var k in envConfig) {
  process.env[k] = envConfig[k];
}

Unfortunately, when i run gatsby develop, NODE_ENV isn't set yet:

error Could not load gatsby-config


  Error: ENOENT: no such file or directory, open 'E:\Front-End Projects\Gatsby\sebhewelt.com\.env.undefined'

It works when I set it manually:

dotenv.parse(fs.readFileSync(`.env.development`));

I need environment variables in gatsby-config because I put sensitive data in this file:

  {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: envConfig.CONTENTFUL_SPACE_ID,
        accessToken: envConfig.CONTENTFUL_ACCESS_TOKEN
      }
    }

How to make it work?

PS: Additional question - As this made me think, I know I shouldn't put passwords and tokens on github, but as netlify builds from github, is there other safe way?

like image 480
Sebastian Avatar asked Nov 03 '17 00:11

Sebastian


2 Answers

I had a similar issue, I created 2 files in the root ".env.development" and ".env.production" but was still not able to access the env file variables - it was returning undefined in my gatsby-config.js file.

Got it working by npm installing dotenv and doing this:

1) When running gatsby develop process.env.NODE_ENV was returning undefined, but when running gatsby build it was returning 'production' so I define it here:

let env = process.env.NODE_ENV || 'development';

2) Then I used dotenv but specify the filepath based on the process.env.NODE_ENV

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

3) Then you can access your variables for your config:

module.exports = {
siteMetadata: {
    title: `Gatsby Default Starter`,
},
plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `${process.env.CONTENTFUL_ID}`,
        accessToken: `${process.env.CONTENTFUL_TOKEN}`,
        },
    },
],
}
like image 90
laij84 Avatar answered Sep 30 '22 16:09

laij84


You should only use env files when you're comfortable checking those into git. For passwords/tokens/etc. add them to Netlify or whatever build tool you use through their dashboard.

These you can access in gatsby-config.js & gatsby-node.js via process.env.ENV_VARIABLE.

You can't access environment variables added this way in the browser however. For this you'll need to use .env.development & .env.production.

like image 34
Kyle Mathews Avatar answered Sep 30 '22 16:09

Kyle Mathews