Serve multiple React applications with Single ASP.NET Core Web Application
The ASP.NET Core is providing amazing experience building Single Page Application with React. You can create a single application either in React or Angular and serve the application using Kestrel. This is made possible with JavaScriptServices
What we are really implementing here is the capability to serve multiple Single Page Applications (Modules) under a single ASP.NET core Web Application
It is a hack, this is an utility can be used with any Client Side JavaScript application or framework with minor customization, you can customize and set your own conventions
-
Every Single Page Application build produces a consistent output with a single HTML Page
-
The HTML page -
index.html
, has references to style bundles and script bundles and a placeholder to render the client side application -
SPAHelper
Class has few helper methods which can extract thehead
andbody
section and render in yourRazor Views
orRazor Pages
RenderReactHead
will extract styles and otherhead
tags and render those in View (You can use layout sections to put that under layout head)
@section Styles { @await Html.RenderReactHead("sample-app-1", "wwwroot/sample-app-1/index.html") }
RenderReactBody
will extract body along with script imports and render those in View
@await Html.RenderReactBody("sample-app-1", "wwwroot/sample-app-1/index.html")
-
The output of SPA build is kept under
sample-app-1
underwwwroot
, you can follow this convention to render multiple SPAs with every Action Method and View -
If you are using React Router, you can add following conditional route mapping to avoid
404 HTTP status code
on page refresh. This will always render server side View before activating client side routingapp.MapWhen( context => context.Request.Path.Value.StartsWith("/Apps/App1"), builder => { builder.UseMvc(routes => { routes.MapSpaFallbackRoute( "spa-app1-fallback", new { controller = "Apps", action = "App1" } ); }); });
Automate build and copying SPA output- Build target for Project to automate publishing with SPA output