Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing .NET Core Environment to React.JS app

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?

like image 283
snappymcsnap Avatar asked Aug 14 '18 18:08

snappymcsnap


People also ask

Can you use .NET core with React?

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).

How do you add an environment variable in React?

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.

Can I use C# in react JS?

React works well with C#. The combination delivers robust apps. React is also one of the most liked libraries by the developer community.


1 Answers

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).

like image 61
Ben Smith Avatar answered Nov 14 '22 00:11

Ben Smith