SPA hosting options with ASP.NET Core: same-origin (static files + MapFallbackToFile or a reverse proxy) versus separate origins (Azure Static Web Apps, CDN), the Vite dev proxy and the .NET SPA templates, and the effect on deep links, caching, CORS, cookies and deployment.
There are two shapes. Same origin: build the SPA into the API's wwwroot, serve it with static files and MapFallbackToFile("index.html") so deep links work, or put both behind one reverse proxy (YARP, Front Door). You get no CORS, first-party cookies and easy BFF security. Separate origins: host the SPA on Azure Static Web Apps or a CDN and call the API on another host. You get independent deploys and edge caching, but you must configure CORS and your cookies become cross-site, pushing you towards tokens in the browser.
Locally, the Vite dev server serves the SPA with hot reload and proxies /api to Kestrel, so the browser sees one origin, just like production same-origin hosting.
The trade-off is security and simplicity (same origin) against independent scaling and release cadence (separate origins).
"My default for a line-of-business app is same origin. The SPA is built by Vite into static files, and either ASP.NET Core serves them from
wwwrootwithMapStaticAssetsand aMapFallbackToFile("index.html"), or a gateway like YARP or Azure Front Door routes/apito the API and everything else to the static files. The browser sees one origin, so there's no CORS, the auth cookie is first-party withSameSite=StrictorLax, and the BFF pattern and antiforgery just work. The fallback is what makes deep links like/orders/42work after a refresh: the server returnsindex.htmland the client-side router takes over.The alternative is separate origins: the SPA on Azure Static Web Apps or a CDN at
app.example.com.auand the API atapi.example.com.au. That's attractive when the frontend team ships several times a day or you need global edge caching. But now every API call is cross-origin, so you configure a strict CORS policy, preflights add latency, and cookies needSameSite=None; Secureor you end up with tokens in JavaScript, which is a weaker security posture. Same site across subdomains helps with SameSite, but it's still cross-origin for CORS.Locally, I run the Vite dev server for hot module replacement and configure its proxy so
/apigoes to Kestrel on its HTTPS port. The browser only talks to Vite, so development mirrors same-origin production. The mistake I see is the fallback catching everything: a typo'd API route returnsindex.htmlwith a 200, and the frontend fails to parse HTML as JSON. I always exclude/apifrom the fallback, and I never letindex.htmlbe cached for long, because that's how users get stuck on an old build."
| Concern | Same origin | Separate origins |
|---|---|---|
| CORS | Not needed | Required; preflights for JSON/auth headers |
| Cookies | First-party, SameSite=Strict/Lax |
Cross-origin: credentials: 'include', often SameSite=None |
| Auth pattern | BFF with cookie session is easy | Tokens in browser or a BFF on the SPA's origin |
| Deploy | One artefact, atomic release | Independent cadence; version skew possible |
| Caching/edge | Front Door or CDN in front of the app | Static host CDN by default |
| Cost | One App Service / container | Static Web Apps is cheap or free for static content |
| Option | When it fits | When not |
|---|---|---|
SPA in API's wwwroot |
Small-to-medium apps, one team | Very high static traffic needing edge caching |
| YARP / Front Door routing to both | Same origin with separate deploys | Small apps where a gateway is overkill |
| Azure Static Web Apps + linked API | Frontend-heavy teams, preview environments per PR | Strict data residency needs not met by the chosen region set; complex auth |
| File | Cache-Control |
|---|---|
assets/index-3f9a1c.js (hashed) |
public, max-age=31536000, immutable |
index.html |
no-cache (revalidate every time) |
| API responses | Decided per endpoint, usually no-store for personal data |
Moving an Angular app from a separate Static Web Apps origin to same-origin hosting behind Front Door removed one CORS preflight per write call (about 60 to 90 ms each from regional Australia), let us switch from tokens in sessionStorage to an HttpOnly cookie session, and fixed stale-build reports by setting no-cache on index.html.
Checks whether the candidate understands how SPA hosting choices affect security, routing, caching and delivery, beyond 'put it on a CDN'.
Green flags
MapFallbackToFile and why deep links need it, and guards /api from itindex.htmlRed flags
AllowAnyOrigin to make things workOrigin = scheme + host + port. https://app.example.com.au and https://api.example.com.au are different origins (CORS applies) but the same site (example.com.au), which matters for SameSite cookies. http://localhost:5173 and https://localhost:7001 are different origins.
Browser ──► Kestrel
├─ /api/** ──► endpoints (JSON)
├─ /assets/*.js ──► static files (long cache)
└─ anything else ──► index.html (fallback, no-cache)
MapStaticAssets() (since .NET 9) serves build-time-known files with compression and ETags based on content hashes. MapFallbackToFile("index.html") adds a low-priority route that matches any path without a file extension that no other endpoint matched. Because it is low priority, API endpoints still win, but an unmatched /api/typo would fall through to it unless you guard it.
React Router and the Angular router use the History API (pushState), so the URL changes without a request. On refresh, the browser requests /orders/42 from the server, which has no such file. The fallback returns index.html, the bundle loads, and the router renders the right screen. Without the fallback the user sees a 404.
Browser ──► Vite :5173 ──┬─ /src, HMR websocket ─► served by Vite
└─ /api/** ─► proxy ─► Kestrel https://localhost:7001
The proxy is server-to-server, so the browser never makes a cross-origin call and CORS is irrelevant in development. Set changeOrigin and secure: false for the dev certificate. Visual Studio's 'React and ASP.NET Core' and 'Angular and ASP.NET Core' templates create a JavaScript project (.esproj) and pre-configure this proxy; Angular uses proxy.conf.json with the same idea. .NET Aspire can run both and inject the API URL.
Every non-simple request (JSON body, Authorization header) triggers an OPTIONS preflight; SetPreflightMaxAge lets browsers cache it. For cookies, the client must send credentials: 'include', the server must reply Access-Control-Allow-Credentials: true with an explicit origin, and the cookie must allow cross-origin sending. Third-party cookie restrictions do not apply when both hosts share a registrable domain (same site), but they do for unrelated domains.
When front and back deploy separately, a user can run yesterday's bundle against today's API. Keep APIs backwards compatible for at least one release, and have the SPA detect a new build (a version.json poll) and prompt a reload. Lazy-loaded chunks from the old build disappear after deploy unless the host keeps previous assets for a while.
npm create vite@latest web -- --template react-ts, add the proxy shown in the code example, and confirm in dev tools that /api calls go to port 5173.wwwroot, add MapFallbackToFile, then refresh on a deep link with and without the fallback./api/typo and see whether you get HTML or a 404; fix it.index.html with curl -I.Same-origin hosting in ASP.NET Core, with an API 404 guard and correct caching, plus the Vite proxy for local development.
// Program.cs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.MapStaticAssets(); // hashed build output from wwwroot: compression + ETags + long cache
var api = app.MapGroup("/api");
api.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new OrderDto(id, "ACME Pty Ltd")));
// Unknown API routes must be a real 404, not index.html.
api.MapFallback(() => Results.Problem(statusCode: StatusCodes.Status404NotFound, title: "No such API endpoint"));
// Everything else is a client-side route: serve index.html, but never cache it long-term.
app.MapFallbackToFile("index.html", new StaticFileOptions
{
OnPrepareResponse = ctx => ctx.Context.Response.Headers.CacheControl = "no-cache",
});
app.Run();
public sealed record OrderDto(int Id, string Customer);
// web/vite.config.ts: the browser talks only to Vite; Vite forwards /api to Kestrel.
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
"/api": {
target: process.env.API_URL ?? "https://localhost:7001",
changeOrigin: true,
secure: false, // accept the local dev certificate
},
},
},
build: {
outDir: "../Api/wwwroot", // same-origin deployment: build straight into the API
emptyOutDir: true,
},
});
// staticwebapp.config.json: the separate-origin option on Azure Static Web Apps
{
"navigationFallback": { "rewrite": "/index.html", "exclude": ["/assets/*", "/api/*"] },
"globalHeaders": { "Cache-Control": "no-cache" },
"routes": [{ "route": "/assets/*", "headers": { "Cache-Control": "public, max-age=31536000, immutable" } }]
}
/api paths. Why it is wrong: Mistyped API calls get index.html with 200, and the client fails with 'Unexpected token <'. Instead: Add an /api fallback returning 404 ProblemDetails, or constrain the SPA fallback.index.html for a long time. Why it is wrong: Users keep loading the old bundle after a release, and its lazy chunks may 404. Instead: no-cache on index.html, long immutable caching on hashed assets.AllowAnyOrigin to get a separate-origin SPA working. Why it is wrong: It cannot be combined with credentials and invites misuse. Instead: List exact origins per environment, or use same-origin hosting.MapFallbackToFile or navigationFallback on Static Web Apps.I treat hosting as a security decision first. Same origin lets me keep tokens out of the browser with a cookie-based BFF, avoid CORS entirely and use SameSite=Strict. That outweighs the convenience of separate static hosting for most internal and B2B apps. When the frontend genuinely needs its own cadence or edge caching, I still try to present one origin to the browser by routing through Front Door or YARP, so the deploys are separate but the origin is shared.
I also check data residency and operations: Azure Static Web Apps content is distributed globally, which is fine for static assets but the API and any personal data should stay in Australia East / Southeast to keep Privacy Act obligations simple.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SPA inside the API (wwwroot) |
One team, one release train | Rebuild API to ship UI | Very high static traffic |
| One origin via gateway (YARP/Front Door) | Separate deploys, shared origin | Gateway to run and configure | Tiny apps |
| Separate origin (Static Web Apps/CDN) | Public, frontend-heavy, frequent UI releases | CORS, cross-site cookies or browser tokens | Apps handling sensitive data with a small team |
The same-origin policy stops JavaScript on one origin (scheme + host + port) from reading responses from another, so a malicious page can't read your bank's API with your cookies. CORS is the server's way to opt in. For a simple request (GET, HEAD or POST with only safelisted headers and a form or text/plain body) the browser sends it and then checks Access-Control-Allow-Origin before handing the response to your code. Anything else, such as a JSON POST, a PUT or an Authorization header, first gets an OPTIONS preflight asking permission for that method and those headers. Sending cookies needs credentials: 'include' and Access-Control-Allow-Credentials: true with an explicit origin. The key trade-off: the browser enforces it but the server's headers decide, and CORS is not security for your API: non-browser clients ignore it.
The API's 80 ms is usually a small part of what users feel: round trips, bytes and browser work dominate. A backend engineer controls a lot of that. Shrink payloads with projection and pagination, and turn on Brotli/gzip (JSON shrinks 70–90%). Use HTTP caching properly: content-hashed JS/CSS get Cache-Control: public, max-age=31536000, immutable, HTML gets no-cache so deploys show up, and API GETs get ETags for cheap 304s. Put static and public content on a CDN like Azure Front Door with Australian points of presence. Enable HTTP/2 and HTTP/3, reduce chatty call sequences, and send preload or 103 Early Hints for critical assets. Then measure with Core Web Vitals at the 75th percentile from real users: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1. Trade-off: aggressive caching is fast but needs versioned URLs or you'll serve stale code.
For a strangler-fig migration, I put a new ASP.NET Core 10 app in front of the legacy ASP.NET Framework 4.8 app. Routes the new app implements are served locally; everything else is forwarded to the legacy app with YARP's MapForwarder as a lowest-priority catch-all. I migrate one vertical slice at a time, using System.Web adapters to share session and authentication, until the legacy app has no traffic and is switched off. Rollback is a route change.
For a backend-for-frontend, the SPA authenticates with an HttpOnly, SameSite cookie to the BFF; the BFF holds the OAuth tokens and attaches access tokens server-side when YARP forwards calls to the APIs, so no token ever reaches browser JavaScript.
The risks are extra latency, shared state coupling the two apps, CSRF on cookie-based calls, and the "temporary" proxy becoming permanent, so I set exit criteria up front.
How to tell it (STAR)
**S:** On [project], our React app for [about 1,500] field staff showed blank screens to some users after every release. **T:** I owned the hosting setup, so I had to find the cause and stop it recurring. **A:** Using dev tools and Application Insights I saw `ChunkLoadError`s and that `index.html` came from disk cache: a blanket rule cached it for a day, so old pages asked for deleted chunks. I set `no-cache` on `index.html`, kept the previous build's assets for a week, added a reload prompt driven by a `version.json` poll, and a post-deploy check on cache headers. **R:** Post-release blank-screen tickets dropped from [about 30] per release to [zero], and the check has caught [one] misconfiguration since.
Last updated 23 Nov 2026.