简体   繁体   中英

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 dotenv@4.0.0

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?

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}`,
        },
    },
],
}

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 .

After doing a few searches, I found that we can set environment variables through netlify website, here are the steps:

  1. Under your own netlify console platform, please go to settings
  2. Choose build & deploy tab (can be found on sidebar)
  3. Choose environment sub-tab option
  4. Click edit variables and add/put your credentials in
  5. Done!

I really dislike the .env.production file pattern, our build system sets up and uses env variables and having extra build steps to write those into a file is weird. But Gatsby only whitelists GATSBY_ of the env vars, with no obvious way of adding your own.

But doing that isn't so hard, you can do it by adding something like this in the gatsby-node.js file:

exports.onCreateWebpackConfig = ({ actions, getConfig }) => {
    const config = getConfig();

    // Allow process.env.MY_WHITELIST_PREFIX_* environment variables
    const definePlugin = config.plugins.find(p => p.definitions);
    for (const [k, v] of Object.entries(process.env)) {
        if (k.startsWith("MY_WHITELIST_PREFIX_")) {
            definePlugin.definitions[`process.env.${k}`] = JSON.stringify(v);
        }
    }

    actions.replaceWebpackConfig(config);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM