I've got a .NET Core 6 Web API and a separate React frontend.
I could deploy them separately into separate subdomains.
But is there a way to combine them into 1 single domain?
That is definitely possible. There are some predefined Visual Studio templates that setup SPA apps like that, but if you already have a Web API project it can be manually setup the same way.
Move your React client app folder into a sub directory in your Web API project. The sub directory name can be anything, but for this example lets call it ClientApp
.
This step gets your development environment setup so that anytime you run your project, to also jump start the React client app server as well.
In your Web API project, install the following NuGet packages in it:
Also in your Web API project, we'll want to add the following configuration into it:
<PropertyGroup>
...
<SpaRoot>ClientApp</SpaRoot>
<SpaProxyServerUrl>http://localhost:3000</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm serve</SpaProxyLaunchCommand>
...
</PropertyGroup>
SpaRoot
being the same folder name we created in step 1.SpaProxyServerUrl
is set to here. This is how Visual Studio will know that your client app is available and launch a browser to.There are a couple things you can do to prepare a production build with this setup.
Have your production build
NPM script output the compiled React app to the wwwroot
folder. Create this folder in your Web API project if it does not already exist.
Add at the very end of the request pipeline in your Program.cs
, add a call to fallback to the default web files (i.e. Index.html) with the following statement:
// Serve up the standard [Index.html] file that is typically created for SPA apps (Angular and React) app.UseDefaultFiles();