Fail Gatsby build if environment variable missing
Asked Answered
M

3

6

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.

Moises answered 12/6, 2020 at 13:24 Comment(0)
F
3

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!

Flannery answered 13/6, 2020 at 20:23 Comment(1)
This is very handy for informing future devs of the data required to build your project :)Pop
M
1

I couldn't find built-in solution for this on Gatsby neither. You may do it manually, but still not too easy.

First problem: If you wanna load your environment from file while running npm script; it can not be loaded right away. But you may trigger a script file, and it can load this environment variables before your check.

lets say build.sh on root directory of project :

source ./.env.development # this line will set env variables
if [ "$API_KEY" = 927349872349798 ] ; then
  npm run build
fi

Another problem rises; some developers might want to run it on windows maybe. So better use famous cross-env package.

npm i cross-env

Then everything is ready, add your secure-build :

  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1",
    "secure-build": "cross-env-shell \"./build.sh\""
  },

And run it :

npm run secure-build

This solution looks too much for me as we created a build.sh and install a new package. Maybe there is cleaner solution. I am not Gatsby Guru after all.

Marileemarilin answered 12/6, 2020 at 19:38 Comment(0)
R
1

I added env checking to the onPreInit life cycle hook in gatsby-node.ts:

const envVariablesList = [
  "ENV1",
  "ENV2",
  "ENV3",

];

function envVarChecker(vars: string[]): string | undefined {
  return vars.find(
    (item) => process.env[item] === undefined || process.env[item] === ""
  );
}

export const onPreInit: GatsbyNode["onPreInit"] = ({ actions }) => {
  const emptyEnv = envVarChecker(envVariablesList);
  if (emptyEnv !== undefined) {
    throw new Error(`Env variable: ${emptyEnv} is empty!`);
  }
};

It fails build almost at the very beginning (during pre-bootstrap phase) if any of the declared variables is missing

Rostov answered 4/12, 2022 at 1:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.