Passing .NET Core Environment to React.JS app

3.2k Views Asked by At

With .NET Core, in Startup.cs you have access to IHostingEnvironment from which you can get the EnvironmentName which corresponds to the value of the ASPNETCORE_ENVIRONMENT environment variable set on the server. This is great for toggling various features on/off as well as using env-specific configs. But with a front-end that is all React.JS, is there a way to pass this value down so that the front-end is aware of it's environment as well? I can think of some potential ways it might be done but they seem a little hacky. What are the best practices for this?

1

There are 1 best solutions below

4
On BEST ANSWER

When you render the page which will host your React app, add the environment variable as a hidden field e.g.

@page
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv

<input id="hostingEnv" 
       type="hidden" 
       [email protected] />

<div id="appRoot"></div>

More info regarding IHostingEnvironment can be found here.

You can then access the value of that hidden variable in your React app using code such as:

const hostingEnv = document.getElementById('hostingEnv').value

As for whether this is "best practice", there's no such thing as best practices only good practices! However this approach has worked for me, though as commenters have suggested there are of course other ways of doing this (e.g. via a separate web request).