📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you host a React or Angular SPA with an ASP.NET Core backend? Compare serving it from the same origin as the API with deploying it to a separate origin, explain how the Vite dev server proxy works locally, and what changes for routing, caching, CORS, authentication and deployment in each case.

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.

Mid-Level Theory Intermediate aspnet-core azure-static-web-apps frontend spa-hosting static-files vite

🎯 Key points

  • Same origin: build output in wwwroot, MapStaticAssets, MapFallbackToFile("index.html") for client-side routes
  • Same origin means no CORS, first-party cookies with SameSite=Strict or Lax, simple BFF and antiforgery
  • Separate origin needs CORS; non-simple calls pay a preflight round trip (cache it with SetPreflightMaxAge)
  • Cross-origin cookie calls need credentials: 'include', an explicit allowed origin, and often SameSite=None; Secure
  • Vite dev server proxies /api to Kestrel so the browser sees one origin in development
  • Fallback must not swallow API 404s: exclude /api from the SPA fallback
  • Cache hashed assets for a year (immutable); serve index.html with no-cache
  • Separate deploys risk version skew: keep APIs backwards compatible and prompt reloads on new builds

⏱ 30-second answer

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

🗣 Full answer (senior)

How I would answer this in an interview

"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 wwwroot with MapStaticAssets and a MapFallbackToFile("index.html"), or a gateway like YARP or Azure Front Door routes /api to 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 with SameSite=Strict or Lax, and the BFF pattern and antiforgery just work. The fallback is what makes deep links like /orders/42 work after a refresh: the server returns index.html and 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.au and the API at api.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 need SameSite=None; Secure or 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 /api goes 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 returns index.html with a 200, and the frontend fails to parse HTML as JSON. I always exclude /api from the fallback, and I never let index.html be cached for long, because that's how users get stuck on an old build."


Same origin vs separate origins

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

Hosting options on Azure

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

Caching rules

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands how SPA hosting choices affect security, routing, caching and delivery, beyond 'put it on a CDN'.

Green flags

  • Explains same origin vs separate origin and the CORS and cookie consequences
  • Knows MapFallbackToFile and why deep links need it, and guards /api from it
  • Describes the Vite or Angular dev proxy and why it avoids CORS locally
  • Sets different cache rules for hashed assets and index.html
  • Mentions version skew and backwards-compatible APIs for separate deploys

Red flags

  • Uses AllowAnyOrigin to make things work
  • Confuses origin with site
  • Has no answer for deep-link refresh 404s
  • Caches everything with the same header

📚 Learn in depth

1. What 'origin' means

Origin = 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.

2. Same-origin hosting inside ASP.NET Core

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.

3. Client-side routing and deep links

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.

4. The Vite dev proxy

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.

5. Separate origins in detail

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.

6. Deployment and version skew

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.

Try it yourself

  1. Create the project with 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.
  2. Build into wwwroot, add MapFallbackToFile, then refresh on a deep link with and without the fallback.
  3. Request /api/typo and see whether you get HTML or a 404; fix it.
  4. Check response headers for a hashed asset and index.html with curl -I.
  5. Host the SPA on a different port without the proxy and watch the CORS preflight in the Network tab.

💻 Code

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" } }]
}

⚠ Common mistakes

  • Mistake: Letting the SPA fallback catch /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.
  • Mistake: Caching 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.
  • Mistake: Enabling 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.
  • Mistake: Configuring CORS in development because the SPA runs on another port. Why it is wrong: Development then differs from production and hides problems. Instead: Use the Vite or Angular dev proxy.
  • Mistake: No server fallback for client-side routes. Why it is wrong: Refreshing a deep link returns 404. Instead: MapFallbackToFile or navigationFallback on Static Web Apps.
  • Mistake: Assuming same site means same origin. Why it is wrong: Subdomains share SameSite treatment but still need CORS. Instead: Decide on origin for CORS and site for cookies separately.
  • Mistake: Deploying front and back separately with breaking API changes. Why it is wrong: Users with old bundles break mid-session. Instead: Keep the API backwards compatible across one release and prompt reloads on new builds.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate chooses separate origins for the SPA and API. Why: Checks preflight, credentials and exposed headers from the browser's side.
    How to answer

    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.

  2. When: Candidate mentions caching headers or a CDN. Why: Checks deeper knowledge of HTTP caching, compression and Core Web Vitals.
    How to answer

    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.

  3. When: Candidate mentions YARP or a gateway to keep a single origin. Why: Checks how YARP is used for a BFF and incremental migration.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Users stuck on an old SPA build after every release
Situation
A React SPA served from an ASP.NET Core App Service in Australia East for [about 1,500 field staff]. Releases went out [twice a week].
Signals
After each release, support tickets reported blank screens and 'ChunkLoadError' in the console; Application Insights browser telemetry showed failed requests for `assets/*.js` files with 404s, mostly in the first hour after deploy.
Investigation
Checked response headers with dev tools and `curl -I`: `index.html` was served with `max-age=86400` because a blanket static-file cache rule applied to every file. Users' browsers kept the old `index.html`, which referenced hashed chunks deleted by the new deployment. The Network tab showed `index.html` coming from disk cache.
Resolution
Immediately: set `Cache-Control: no-cache` on `index.html` via the fallback's `OnPrepareResponse` and redeployed. Properly: kept the previous build's assets for 7 days in the deployment, added a `version.json` poll that prompts users to reload when a new build is live, and catch dynamic import failures to trigger one automatic reload.
Prevention
A smoke test after deploy asserts the cache headers on `index.html` and a hashed asset; an Application Insights alert on browser 404s for `/assets`; a hosting checklist in the repo's ADR.

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.

↩ Usually asked after

More in SPA Integration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me