Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing NODE_ENV environment variable in React on Rails

I've got a React on Rails application that hits an API. I want to configure the API endpoint to localhost for development and to my deployed app's URL for production.

client/package.json

 "scripts": {
    "build:production": "NODE_ENV=production webpack --config webpack.config.js",
 },

client/webpack.config.js

const devBuild = process.env.NODE_ENV !== 'production';

const config = {
  entry: [
    'es5-shim/es5-shim',
    'es5-shim/es5-sham',
    'babel-polyfill',
    './app/bundles/Main/startup/registration',
  ],
  output: {
    filename: 'webpack-bundle.js',
    path: __dirname + '/../app/assets/webpack',
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
  ]
}

I see that process.env.NODE_ENV is available in config/webpack.config.js (used here to add source map devtools to the module exports), but I'd like a way to see what the environment is in my React code somewhere in client/. What are my options if any?

like image 984
Matthew Hinea Avatar asked Feb 27 '26 06:02

Matthew Hinea


1 Answers

I just used process.env.NODE_ENV in a Redux action file successfully. I'm exporting NODE_ENV in webpack with plugin definition shown below in webpack.config.js:

plugins: [
    ...
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('ENV_VALUE')
        }
    })
]
like image 125
Sun Lee Avatar answered Mar 01 '26 11:03

Sun Lee