4

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>
    )
  }
}
Lalas M
  • 1,116
  • 1
  • 12
  • 29

1 Answers1

0

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',
      }),
    ],
  })
}
bamse
  • 4,243
  • 18
  • 25
  • I was not using this .. But "MY_FANCY_VARIABLE" is declared in the gatsby-node.js file or is it taking from the .env file ? – Lalas M Jun 02 '21 at 06:08
  • It is defined in `gatsby-node.js` but in `gatsby-node` you have access to your OS variables so you can make them available in your app. The idea behind this is maybe you don't want all you variables available in the app. – bamse Jun 02 '21 at 06:09