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?
Passing .NET Core Environment to React.JS app
Asked Answered
Could make an API endpoint that the React app could interrogate for this information. –
Finlay
Asking for best practices will only result in subjective answers. Be more specific. You say you can think of ways it might be done...perhaps tell us these ways or show us what you've already tried. –
Reform
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).
that was along the lines of what I was thinking but that's a much more elegant way to do it than I was envisioning, thanks for the help –
Linnie
No problem @snappymcsnap. Glad I could help :) –
Bilge
How would this work if all the files are in the ClientApp folder and the index.html page is not a compiled page? Can we rewire the npm build that compiles the static site to use a .cshtml page instead as the first page? –
Estis
I use Asp.Net Core's default template for a React SPA. The "page which will host your React app" is not a
.cshtml
file. I think this matches @Nissan's question. –
Persimmon © 2022 - 2024 — McMap. All rights reserved.