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?
The ASP.NET Core with React project template provides a convenient starting point for ASP.NET Core apps using React and Create React App (CRA) to implement a rich, client-side user interface (UI).
To set a custom environment variable, simply set it while starting the Create React App build process. Here REACT_APP_TEST_VAR is the custom environment variable and we are setting it to the value 123 . In our app we can access this variable as process. env.
React works well with C#. The combination delivers robust apps. React is also one of the most liked libraries by the developer community.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With