Search code examples
javascriptenvironment-variablesgatsbydotenv

Fail Gatsby build if environment variable missing


I have experimented with adding environment variables to my Gatsby project using .env.development and .env.production files and it's working great.

I would like to have my builds fail if one of the environment variables is missing, however I can't seem to see how to enable this functionality.

I have read through the Gatsby environment variables documentation, but can't seem to see how this would work? is this possible?

I believe it uses dotenv/webpack define plugin under the hood.


Solution

  • I’m sure there are other ways to do this, but with some quick tests, this approach seems to be working well for me.

    In your gatsby-config.js file, you can choose to explicitly require the dotenv, so you can use those environment variables in your config.

    I added the following, and now the Gatsby build will fail unless the specified environment variables are present.

    // Load the environment variables, per
    // https://www.gatsbyjs.org/docs/environment-variables/#server-side-nodejs
    require('dotenv').config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    
    function checkEnv(envName) {
      if (typeof process.env[envName] === 'undefined' || process.env[envName] === '') {
        throw `Missing required environment variables: ${envName}`
      }
    }
    
    try {
      checkEnv('NODE_ENV')
      checkEnv('EXAMPLE_MISSING_ENV')
      checkEnv('EXAMPLE_API_KEY')
    } catch (e) {
      throw new Error(e)
    }
    
    // The rest of the config file
    

    I could imagine customizing this further, ex. logging a warning for a variable with a fallback versus throwing an error for one that is required by your content sourcing plugin or theme. Hope this is helpful as a starting point!