1

Is there any way in React to tell what environment I am in at runtime without exposing all my process.env variables to the client?

Webpack allows me to expose environment variables to the client, which is dangerous.

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    // dev code
} else {
    // production code
}
console.log('here come all my secrets: ', {process.env});

I am aware, this question has already been asked in context of Webpack, but I am trying to avoid a complex build configuration.

Is there any simpler solution?

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Florian
  • 33
  • 7
  • Does this answer your question? [Detecting production vs. development React at runtime](https://stackoverflow.com/questions/35469836/detecting-production-vs-development-react-at-runtime) – Shivangam Soni Nov 25 '22 at 09:45
  • Can't you just expose `process.env.NODE_ENV` through webpack without exposing the rest of `process.env`? – Guillaume Brunerie Nov 26 '22 at 12:54

1 Answers1

0

OK I have found a solution:

You can simply check if minifying has been enabled for your js code, which would only be the case in production. E.g. I have disabled logging with this simple trick. The element.type.name will be renamed by minifying.

const MyElement = ({isProduction}) => (<div>Environment: {isProduction?'Production':'Development'}</div>);

const MyElementEl = React.createElement(MyElement);
const isProduction = (MyElementEl.type.name !== 'MyElement');

if(isProduction) //will be true when your js sources are minified 
    console = { ...console, logX: console.log, log: () =>{ } };
    
ReactDOM.render(<MyElement isProduction={isProduction}/>, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
<div id="app" />
</body>
Florian
  • 33
  • 7