Search code examples
.net-coredeploymentasp.net-core-webapi

Combine frontend with .NET Core API into a single domain


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?


Solution

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

    Step 1: Move Your SPA Front-End Files Into Your Web API Project

    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.

    Step 2: Setup Your Web API Project To Spin Up Your React App On Start

    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:

    • Microsoft.AspNetCore.SpaProxy
    • Microsoft.AspNetCore.SpaServices.Extensions

    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>
    
    • Note the SpaRoot being the same folder name we created in step 1.
    • The SPA proxy launch command can be any NPM script that you wish to use that actually launches the client app server. Ensure that the script also uses the same port that the SpaProxyServerUrl is set to here. This is how Visual Studio will know that your client app is available and launch a browser to.
    • Note that the above configuration is purely for local development only.

    Step 3: For Production Builds...

    There are a couple things you can do to prepare a production build with this setup.

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

    2. 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();