AspNetCore.SpaYarp 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package AspNetCore.SpaYarp --version 1.1.0                
NuGet\Install-Package AspNetCore.SpaYarp -Version 1.1.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AspNetCore.SpaYarp" Version="1.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AspNetCore.SpaYarp --version 1.1.0                
#r "nuget: AspNetCore.SpaYarp, 1.1.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AspNetCore.SpaYarp as a Cake Addin
#addin nuget:?package=AspNetCore.SpaYarp&version=1.1.0

// Install AspNetCore.SpaYarp as a Cake Tool
#tool nuget:?package=AspNetCore.SpaYarp&version=1.1.0                

AspNetCore.SpaYarp

NuGet
Supported ASP.NET Core versions: 3.1, 5.0, and 6.0

With ASP.NET Core Preview 4, the ASP.NET Core team introduced a new experience for SPA templates. The main benefit of this new experience is that it�s possible to start and stop the backend and client projects independently. This is a very welcome change and speeds up the development process. But it also includes another more controversial change. The old templates served the client application as part of the ASP.NET Core host and forwarded the requests to the SPA. With the new templates, the URL of the SPA is used to run the application, and requests to the backend get forwarded by a built-in proxy of the SPA dev server.

AspNetCore.SpaYarp uses a different approach. Instead of using the SPA dev server to forward requests to the host/backend, it uses YARP to forward all requests that can't be handled by the host to the client application. It works similar to the old templates, but with the advantage of the new templates to start and stop the backend and client projects independently.

The following graphic shows the differences:

Overview

To get more insights you can read my blog post An alternative approach to the ASP.NET Core SPA templates using YARP.

Running the sample

To run the sample, open the solution in Visual Studio and start the AspNetAngularSpaYarp project. It reuses an existing SPA dev server if the client app is already running (started manually in a terminal or VS Code) or it starts a new one.

Debugging

It's possible to debug the .NET code and the SPA at the same time with different editors. To use Visual Studio Code to debug the SPA, create a launch.json file as described in the docs. But instead of the URL of the SPA, the URL of the .NET host must be used.

This is the launch.json file used in the ASP.NET Core 6 sample:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-msedge",
      "request": "launch",
      "name": "Launch Edge against localhost",
      "url": "https://localhost:7113",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

Using AspNetCore.SpaYarp

Configure settings in project file

<PropertyGroup>
    
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaClientUrl>https://localhost:44478</SpaClientUrl>
    <SpaLaunchCommand>npm start</SpaLaunchCommand>
    
    
</PropertyGroup>

ASP.NET Core 6.0 (with WebApplication builder)

Use AddSpaYarp() to register the services and UseSpaYarp() to add the middlware and configure the route endpoint.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
// This file gets not published when using "dotnet publish".
// The services get not added and the proxy is not used when the file does not exist.
builder.Services.AddSpaYarp();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

// The middlewares get only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
app.UseSpaYarp();

// If the SPA proxy is used, this will never be reached.
app.MapFallbackToFile("index.html");

app.Run();

ASP.NET Core 3.1, 5.0, and 6.0 (with Startup.cs)

Use AddSpaYarp() to register the services, UseSpaYarpMiddleware() to add the middlware, and MapSpaYarp() to configure the route endpoint.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        // Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
        // This file gets not published when using "dotnet publish".
        // The services get not added and the proxy is not used when the file does not exist.
        services.AddSpaYarp();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        // The middleware gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
        app.UseSpaYarpMiddleware();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            // The route endpoint gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
            endpoints.MapSpaYarp();

            // If the SPA proxy is used, this will never be reached.
            endpoints.MapFallbackToFile("index.html");
        });
    }
}

Migrate from SpaProxy

This guide assumes that you are using the default ASP.NET Core with Angular Template (but should work the same for other frameworks too).
Thanks to @mdowais for this guide.

Step 1: Add the Nuget Package
https://www.nuget.org/packages/AspNetCore.SpaYarp

Step 2: Remove Old SpaProxy Package
Remove the Package Microsoft.AspNetCore.SpaProxy. As it is not needed for this implementation.

Note: The default template adds a Environment Variable ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", in the launchSettings.json (Debug Properties in Visual Studio). Which has to be removed, so that you don't see an annoying Exception thrown that "Microsoft.AspNetCore.SpaProxy" is 404.

Step 3: Remove proxy.conf.js
Remove the proxy.conf.js file that contains the proxy config for the client dev server.
And remove the reference to this file from the angular.json file too.

Step 4: Change Project Properties
In your Project Settings (csproj) → PropertyGroup, change the following

SpaProxyServerUrl to SpaClientUrl
SpaProxyLaunchCommand to SpaLaunchCommand

Step 5: Add the Services and Usings in your Program.cs

// First
builder.Services.AddSpaYarp()

//Second
app.UseSpaYarp();
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.