Using Environmental Variables

Environmental Variables ??

could also be different for individual users on the same computer.

Environmental Variables

They are useful when:

  • Values are different on developer computers
  • Values are different across multiple environments: ie... (development & production)
  • Values change frequently and are highly dynamic

They are great at pointing to external services and servers, or storing passwords or other credentials.

But for our discussion we will limit it to Gastby and Node.js using development and production environments , which Gatsby supports by default to create a blazing fast website!

In Javascript, APIs and third-party apps need to use 'config' data called environmental or configuration variables in the form of NAME=VALUE. For example, when adding search with Algolia to Gatsby, Algolia ID and API keys must be set as environmental variables. The variables are placed in a .env file you create, located in the root directory of your app.



The .env file should added to your .gitignore file, so Git source control at runtime will ignore this file to keep your secrets safe.

The process.env global variable is injected by the Node.js at runtime for your application (client-side code) to use and it represents the state of the system environment your application is in when it starts. For example, if the system has a ALGOLIA_APP_ID variable set, this will be made accessible to you through Node process.env.ALGOLIA_APP_ID which allows Algolia to index Gatsby content.

Note that since these variables are embedded at build time, you will need to restart your dev server or rebuild your site after changing them.

Gatsby runs several Node.js scripts at build time, notably gatsby-config.js and gatsby-node.js

The Dotenv module is required to load environmental variables from your .env file, which comes installed with Gatsby. An example of using it is...



plugins: [
      resolve: `gatsby-plugin-algolia`,
      options: {
        appId: process.env.GATSBY_ALGOLIA_APP_ID,
        apiKey: process.env.ALGOLIA_ADMIN_KEY,

Your application now has access to environmental variables.

You can verify your application has access to the environmental variables using the process.env object by calling