Server-side environment variables

Unlike other implementations that leverage universal JavaScript, Gatsby performs all compilation at build time, which means that only those scripts executed during the build will provide environment variables on the server side. More specifically, Gatsby runs a few Node.js scripts in succession during the build-time compilation process, including the logic found in gatsby-config.js and gatsby-node.js.

Because Node.js has access to OS-level environment variables while it is executing, environment variables can be added:

  • By adding them before NPM scripts in the command line
  • By providing them to an infrastructure provider
  • Within the operating system itself

In a Linux terminal (or on macOS), you can add an environment variable to an arbitrary NPM script as follows:

$ MY_ENV_VAR=bar npm run develop

Unlike client-side project environment variables exposed to the browser as part of Gatsby’s creation of a client bundle, server-side environment variables will not be automatically detected when Node.js scripts are executed. Thus, it’s strongly recommended that you use the dotenv library to introspect the available .env.* files and include those values in the NPM scripts’ execution. Since dotenv is already a defined dependency in Gatsby’s package.json file, you don’t need to install it separately and can instead require it in your gatsby-config.js or gatsby-node.js file as follows:

// gatsby-node.js
require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

These values are now available through process.env, a global variable injected into Node.js upon its execution, as we saw in the previous section with client-side environment variables.

NOTE

Gatsby developers leveraging Windows operating systems for development need to undertake a slightly different approach for server-side OS-level environment variables included in a terminal command.


Posted

in

,

by

Tags:

Comments

Leave a Reply

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