How to access environment variables inside Gatsby build files that are served using gatsby-plugin-nodejs

Viewed 1072

I have a GatsbyJS application that is served by NodeJS express server using gatsby-plugin-nodejs. I set an env variable in my Cloud foundry as GATSBY_MY_ENVIRONMENT="Production".

My NodeJS is using express and which have the following code.

const express = require('express');
const app = express();
const gatsby = require("gatsby-plugin-nodejs")
const cfenv = require('cfenv');
const appEnv = cfenv.getAppEnv();
require('dotenv').config()
...
gatsby.prepare({ app }, () => {})
app.listen(appEnv.port, '0.0.0.0', function () {
    console.log("server starting on " + appEnv.url);
    console.log("My Gatsby env variable " + process.env.GATSBY_MY_ENVIRONMENT);
});

I'm able to console log my variable value - Production using console.log(process.env.GATSBY_MY_ENVIRONMENT) in the NodeJs express but I'm not able to get this value inside my Gatsby components.

My gatsby-config.js has the following added

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

How can I access this variable inside my GatsbyJS component on build? The component which I'm trying to access this variable may look like

import React from 'react';
import Header from 'gatsby-theme-carbon/src/components/Header';

export default class MyComponent extends React.Component {
  render() {
    return (
      <div>
        My environment is {process.env.GATSBY_MY_ENVIRONMENT}
      </div>
    )
  }
}
1 Answers

Have you tried using webpack's DefinePlugin to make your environment variables available in your app?

Details on accessing environment variables in JavaScript

This means adding a gatsby-node.js - or editing it if you already use it (details):

exports.onCreateWebpackConfig = ({
  plugins,
  actions,
}) => {
  actions.setWebpackConfig({
    plugins: [
      plugins.define({
        MY_FANCY_VARIABLE: 'the-value',
      }),
    ],
  })
}
Related