The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·31

Frontend Deployment

Getting frontends to users: static hosting and object storage, CDNs, SPA fallback, SSR hosting on Node, serverless and edge runtimes, Docker and reverse proxies, TLS, immutable assets and cache invalidation, environment configuration, and safe rollout and rollback.

29 topics · ~23 min read · 26-question quiz
Updated Suggest a correction

Start here: putting a frontend on the internet

Deployment is copying files somewhere users can reach

After npm run build, a frontend is a folder of files: an index.html, some hashed JavaScript and CSS, images and fonts. Deploying means making those files available at your domain, quickly, everywhere, and replacing them safely when you release a new version. There are two broad shapes:

Shape What runs in production Typical hosts
Static (CSR or SSG sites, chapter 24) nothing but a file server; all logic runs in the browser object storage (Amazon S3, Google Cloud Storage, Azure Blob) behind a CDN; Netlify, Vercel, Cloudflare Pages, GitHub Pages
Server-rendered (SSR, Server Components) a Node (or Deno/Bun) server, serverless functions or edge functions, plus static assets Vercel, Netlify, Cloudflare Workers, AWS (Lambda, ECS), a container platform (Kubernetes, Cloud Run) behind a load balancer

Even server-rendered apps serve most of their bytes (JavaScript, CSS, images) as static files, so both shapes share the same core practices.

CDNs: copies near every user

A CDN (content delivery network) is a worldwide network of caching servers. A user in Chennai fetches your files from a nearby CDN location instead of from your origin server in Mumbai or Virginia: light in fibre needs about 1 ms per 200 km (Volume 1 chapter 9), so distance alone can add 100–200 ms per round trip to a far-away origin. The CDN follows your Cache-Control headers (chapter 19), so getting caching right is most of getting deployment right:

File Header Why
assets/index-Cs1vsncV.js, CSS, fonts, hashed images Cache-Control: public, max-age=31536000, immutable the name changes whenever the content does, so caches can keep it forever
index.html (and other HTML) Cache-Control: no-cache (or a short max-age plus revalidation) it's the entry point that names the current assets; it must update on every deploy
API responses depends: usually private, no-store for user data never let a shared cache serve one user's data to another

Single-page apps need a fallback route

A client-side router (chapter 24) handles URLs like /orders/42 in the browser, but when someone opens that link directly, the browser asks the server for /orders/42, and a plain file server has no such file. The host must answer page routes with index.html (an SPA fallback) so the app can start and route itself. But only page routes: a request for a missing asset must still return 404. The lab shows the common misconfiguration where every unknown path, including /assets/missing-123.js, returns index.html with status 200, which turns a clear "file not found" into a baffling browser error: Unexpected token '<' for a classic script, or "Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of \"text/html\"" for a module (both measured in Chromium).

Releasing a new version safely

Users have your app open while you deploy. Their page was built from the old index.html, which references old file names, and single-page apps keep loading code chunks long after the first page load (chapter 27's code splitting). The lab deployed version 2 while a user had version 1 open and deleted version 1's files:

Text
user opened: app v1
after deploying v2 and deleting v1's assets, user clicks Orders →
  ERROR: Failed to fetch dynamically imported module: http://localhost:8112/assets/orders-c93bc377.js

That error (and its webpack cousin, ChunkLoadError) is one of the most common production errors in SPAs, and it happens on every deploy to whoever is mid-session. The fixes:

  1. Keep old hashed assets for days or weeks after a deploy (an object store or CDN that you only ever add to makes this natural). Because names are unique, old and new files never conflict.
  2. Switch releases atomically: upload the complete new release first, then switch which index.html is served in one step, instead of copying files over the live folder one by one.
  3. Handle the error gracefully: if a chunk still fails to load, show "A new version is available" and reload.

Configuration: build once, deploy everywhere

The same build should go to staging and production; only configuration differs (API URLs, feature flags, analytics keys). Values baked in at build time (import.meta.env.VITE_API_URL) force a rebuild per environment, and the artefact you tested isn't the one you ship. The common alternative is a small runtime config file (/config.json) or values injected into index.html by the server, read when the app starts. Either way, nothing in frontend configuration is secret: anything the browser receives, users can read.

Rollouts and rollbacks

Because a static release is just a set of files plus "which index.html is current", rolling back is switching that pointer back, which takes seconds. Platforms add preview deployments (every pull request gets its own URL for review), gradual rollouts (send 5% of users to the new version first, watching error rates; chapter 32) and feature flags (ship code dark, turn features on per user or region without deploying).

How deep to go in frontend deployment

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain static vs server-rendered hosting, CDNs, cache headers and SPA fallbacks
L2 Deploy a static site and an SSR app with correct headers, HTTPS, custom domains and preview deployments
L3 Explain atomic releases, immutable assets, cache invalidation, serverless and edge runtimes, containers and reverse proxies
L4 Diagnose stale caches, chunk-load errors, wrong content types, broken fallbacks and TLS problems
L5 Design release strategy: runtime configuration, gradual rollouts, feature flags, multi-region hosting
L6 Operate it: CDN cost and hit ratio, rollback drills, release observability, compliance (data residency)

Static frontends

Static hosting

A built SPA or SSG site is just files: HTML, JS, CSS, images and fonts. Static hosting serves them as-is, which makes it the cheapest, fastest and most reliable way to deploy a frontend:

Option Notes
Object storage + CDN (S3 + CloudFront, GCS + Cloud CDN, Azure Blob + Front Door, Cloudflare R2 + CDN) The cloud-native default: cheap, durable, global
Jamstack platforms (Netlify, Vercel, Cloudflare Pages, Azure Static Web Apps, GitHub Pages, Firebase Hosting) Git-push deploys, preview deployments per PR, built-in CDN, redirects and headers config, serverless functions alongside
Nginx/Caddy on a VM or container Full control; you run it
Any web server serving dist/ Spring Boot can serve src/main/resources/static, which works for small internal apps but couples deploy cycles

Object storage

Object storage (S3 and equivalents, Vol. 8) stores files as objects under keys in buckets, with metadata: Content-Type, Cache-Control, Content-Encoding. For frontend hosting:

  • Keep the bucket private. Serve through the CDN using origin access control (CloudFront OAC) or signed origin requests. A public bucket bypasses your CDN's headers, WAF and logging, and leaked public buckets are a classic data-exposure incident.
  • Set metadata per file at upload: the correct Content-Type (.wasm must be application/wasm, .mjs text/javascript, fonts font/woff2), Cache-Control per file class (below), and Content-Encoding: br for precompressed files if you upload them that way.
  • Upload in the right order for zero-downtime deploys: hashed assets first, HTML last (see immutable assets below).
  • Enable versioning for rollback and accident recovery.
Terminal
# Deploy a Vite/Angular build to S3 behind CloudFront
$ aws s3 sync dist/assets s3://shop-web/assets --cache-control "public,max-age=31536000,immutable"
$ aws s3 cp dist/index.html s3://shop-web/index.html --cache-control "no-cache"
$ aws cloudfront create-invalidation --distribution-id E123 --paths "/index.html"

CDN

The CDN (chapter 27) is the front door: TLS termination, HTTP/2 and HTTP/3, compression, caching at the edge, DDoS absorption, a WAF, redirects and header rules, and image optimisation. Configuration that matters for frontends:

  • Cache policy per path: /assets/* cached for a year at the edge and in browsers; HTML cached briefly at the edge (or no-cache plus validation); /api/* usually not cached, or cached per explicit rules.
  • Cache key: exclude irrelevant query strings, cookies and headers from the cache key (more hits), but include anything that changes the response (Accept-Encoding, and Accept if you negotiate image formats).
  • Security headers at the edge (CSP, HSTS, frame-ancestors and so on, chapter 28) through response-header policies or edge functions.
  • Origin shielding: a single mid-tier cache in front of the origin to reduce origin load.
  • Logs and metrics: hit ratio, 4xx and 5xx rates, bytes served by country.

SPA fallback

A client-side-routed SPA has one real HTML file. If a user loads or refreshes https://shop.example.com/orders/42, the server looks for a file /orders/42, finds nothing, and returns 404. You need a fallback: for any path that isn't a real file, serve index.html and let the client router handle it.

Nginx
# Nginx
location / {
  try_files $uri $uri/ /index.html;          # real file → serve it; otherwise index.html
}
location /assets/ {
  try_files $uri =404;                        # missing assets must 404, NOT return index.html
  add_header Cache-Control "public, max-age=31536000, immutable";
}
TOML
# Netlify (_redirects equivalent in netlify.toml)
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200          # a rewrite, not a redirect: the URL stays /orders/42

Pitfalls:

  • Don't fall back for asset paths. If /assets/app.old.js is missing (after a deploy) and the server returns index.html with status 200, the browser tries to execute HTML as JavaScript: Uncaught SyntaxError: Unexpected token '<'. Assets must 404.
  • With S3 + CloudFront, mapping 403/404 errors to /index.html with a 200 affects all paths, including missing assets and API errors. Prefer a CloudFront Function or edge rule that rewrites only extensionless paths.
  • Real 404s: the SPA router should render a not-found page. For SEO, crawlers then see a 200 for nonexistent URLs, which SSR or SSG frameworks handle better.
  • Deep links need the right <base href> / router base path when the app is served under a sub-path (/app/).

Server-rendered frontends

SSR hosting and Node runtimes

SSR frameworks (Next.js, Nuxt, SvelteKit, Angular SSR, Remix/React Router, Astro SSR) need a server process, almost always Node.js (or Bun or Deno), plus the static assets on a CDN. Running Node in production:

  • Node versions: use an LTS release (even-numbered: 22, 24), and pin it (.nvmrc, engines, Docker base image tag). Odd-numbered releases are short-lived.
  • Process model: Node runs JavaScript on one thread per process (the event loop, chapter 15). Use multiple cores by running several processes: container replicas, PM2 cluster mode, or Node's cluster module. Container orchestration (one process per container, many replicas) is the usual answer.
  • Memory: set --max-old-space-size to fit the container limit (Vol. 1 ch. 8's OOM kill), and monitor heap growth, because memory leaks in SSR (module-level caches growing per request) are common.
  • Don't block the event loop with heavy synchronous work in request handlers (big JSON, sync crypto, sync file I/O). One slow render stalls every concurrent request on that process. Measure event-loop lag.
  • Graceful shutdown on SIGTERM (Vol. 1 ch. 8): stop accepting connections, finish in-flight requests, then exit. Kubernetes sends SIGTERM before SIGKILL.
  • Health endpoints (/healthz for liveness, /readyz for readiness) for load balancers and orchestrators.
  • Caching in front: a CDN for cacheable pages, and the framework's data and ISR caches backed by shared storage when running several instances (chapter 24).

Serverless

Serverless functions (AWS Lambda, Google Cloud Run functions, Azure Functions, and Vercel and Netlify Functions, which run on Lambda underneath) run your SSR or API code per request, scaling to zero and up automatically, and billed per invocation and duration.

  • Pros: no servers to manage, automatic scaling, pay per use, natural fit for spiky traffic, preview environments per branch.
  • Cons: cold starts (initialising a Node runtime plus your bundle takes 100 ms to over 1 s; keep bundles small, use provisioned concurrency, or snapshotting), execution limits (timeouts, payload sizes, response streaming support varies), database connections (thousands of short-lived functions exhaust a Postgres connection pool: use connection poolers such as PgBouncer or RDS Proxy, or HTTP-based database drivers), cost at sustained high traffic (where containers become cheaper), and vendor-specific behaviour.
  • Next.js on Vercel maps each route to functions automatically. Elsewhere, adapters (OpenNext, SvelteKit adapters, Nitro presets) produce function bundles.

Container-based serverless (Google Cloud Run, AWS App Runner, Azure Container Apps, Fly.io) runs ordinary Docker images that scale to zero. It's often the best middle ground for SSR: a normal Node server, with fewer limits and concurrency per instance (many requests per container, unlike Lambda's one).

Edge runtimes

Edge runtimes (chapter 24: Cloudflare Workers, Vercel Edge, Deno Deploy, Netlify Edge, Fastly Compute) run code in V8 isolates at hundreds of locations:

  • Isolates instead of containers: thousands of tenants share one process, each in a lightweight V8 isolate, so cold starts are around 1–5 ms.
  • Web-standard APIs only: fetch, Request/Response, URL, Web Crypto, streams, caches. No (or limited) Node built-ins, no native modules, restricted file access, and CPU-time limits per request (tens of milliseconds to seconds).
  • Data access must be HTTP-friendly or edge-native: Cloudflare KV, D1 and Durable Objects, Turso/libSQL, Upstash Redis, globally replicated stores, or a regional database (with the latency trade-off of chapter 24).
  • Best for: middleware-style logic (redirects, rewrites, auth checks, A/B bucketing, geolocation, header manipulation), personalising cached pages, lightweight APIs, and streaming proxies to AI APIs.

Docker for frontends

Containerising SSR apps (and sometimes static ones behind Nginx) gives you one artifact for every environment (Part VI covers containers in depth):

Dockerfile
# Multi-stage build for a Next.js standalone app (pattern applies to any Node SSR framework)
FROM node:24-alpine AS deps
WORKDIR /app
RUN corepack enable
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile                    # cached layer unless the lockfile changes

FROM node:24-alpine AS build
WORKDIR /app
RUN corepack enable
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build                                         # next.config: output: "standalone"

FROM node:24-alpine AS run
WORKDIR /app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0     # bind all interfaces inside the container (Vol. 1 ch. 9)
RUN addgroup -S app && adduser -S app -G app
COPY --from=build --chown=app:app /app/.next/standalone ./
COPY --from=build --chown=app:app /app/.next/static ./.next/static
COPY --from=build --chown=app:app /app/public ./public
USER app                                               # don't run as root
EXPOSE 3000
HEALTHCHECK CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1
CMD ["node", "server.js"]                              # node as PID 1: handle SIGTERM (or use --init / tini)
Dockerfile
# Static SPA served by Nginx
FROM node:24-alpine AS build
WORKDIR /app
COPY . .
RUN corepack enable && pnpm install --frozen-lockfile && pnpm build

FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf          # SPA fallback + cache headers + gzip/brotli
COPY --from=build /app/dist /usr/share/nginx/html

Practices: multi-stage builds (small final images without build tools or devDependencies), a pinned base image digest, non-root user, a .dockerignore (exclude node_modules, .git and .env), multi-arch images (linux/amd64 + linux/arm64 for Graviton and Apple Silicon, Vol. 1 ch. 7), image scanning (Trivy, Grype), and a read-only root filesystem where possible.

Reverse proxies

A reverse proxy (Nginx, Caddy, Envoy, Traefik, HAProxy, or a cloud load balancer) sits in front of your app servers:

  • TLS termination and certificate management (Caddy and Traefik automate it with ACME).
  • Routing: /api/* → the Spring Boot backend, /* → the Next.js server or static files. One origin for frontend and API removes CORS (chapter 19).
  • Load balancing across instances, health checks, retries and timeouts.
  • Compression, static file serving, caching (proxy_cache), rate limiting, request size limits, and buffering control (disable buffering for SSE and streaming SSR).
  • Headers: security headers, and the X-Forwarded-For/X-Forwarded-Proto/Forwarded headers that tell the app the original client IP and scheme. Configure the app to trust them only from the proxy (Spring's server.forward-headers-strategy, Express's trust proxy), or attackers can spoof client IPs.
Nginx
server {
  listen 443 ssl;
  http2 on;
  server_name shop.example.com;
  ssl_certificate     /etc/letsencrypt/live/shop.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/shop.example.com/privkey.pem;

  add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
  add_header X-Content-Type-Options nosniff always;

  location /api/ {
    proxy_pass http://spring_backend;               # upstream block with several instances
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_read_timeout 30s;
  }
  location /api/stream/ {
    proxy_pass http://spring_backend;
    proxy_buffering off;                             # SSE / streaming must not be buffered
    proxy_read_timeout 1h;
  }
  location / {
    proxy_pass http://next_frontend;                 # SSR app
  }
}

TLS

Every production frontend must be HTTPS-only (Vol. 1 ch. 9): secure contexts are required for service workers, geolocation, the clipboard and HTTP/2 and HTTP/3. Browsers mark HTTP pages "Not secure", and network attackers can inject scripts into HTTP pages. Checklist:

  • Automate certificates: ACME (Let's Encrypt, ZeroSSL) through Caddy, cert-manager in Kubernetes, or cloud-managed certificates (AWS ACM, Google-managed). Certificate lifetimes are shrinking toward 47 days (Vol. 1 ch. 9), so manual renewal isn't viable.
  • Redirect HTTP → HTTPS (301) and send HSTS. Submit to the HSTS preload list once you're sure every subdomain supports HTTPS.
  • TLS 1.2+ only, with modern cipher suites (Mozilla's SSL Configuration Generator), OCSP stapling, HTTP/2, and HTTP/3 where supported.
  • Monitor expiry (alerts at 14 days), and check with SSL Labs.
  • CAA records limit which CAs may issue certificates for your domain.

Releases and configuration

Immutable assets

Because HTML references assets by content-hashed URL (/assets/app.3f9a1c.js), every build produces new asset files while old ones remain valid. That gives atomic, zero-downtime deploys:

1. upload new assets app.3f9a1c.js (v1)app.77d0e2.js (v2) ← newchunk-cart.9ab1.js (v2) 2. switch index.htmlnow references v2(no-cache: users get iton next navigation) 3. later: prune v1after a grace period(days, not minutes) an open tab still running v1 lazy-loads chunk-orders.v1.js → must still exist delete old assets now → ChunkLoadError ("Failed to fetch dynamically imported module") rollback = point index.html back at v1 assets (still present)
Immutable deployment. Upload new hashed assets alongside old ones, then switch the HTML. Users mid-session keep loading their old chunks.
  1. Upload new hashed assets first. They don't overwrite anything.
  2. Switch the HTML (the one non-hashed, no-cache file) to reference them, atomically.
  3. Keep old assets for a while. Users with an open tab running the previous version still lazy-load their old chunks. Deleting them immediately causes ChunkLoadError / "Failed to fetch dynamically imported module" errors after deploys, which is one of the most common frontend production errors. Handle it gracefully too: catch chunk load errors and reload the page once.
  4. Rollback is just pointing the HTML back at the previous version's assets.

Version skew also affects APIs and Server Functions. An old client may call a new backend. Keep API changes backward compatible (expand/contract, Vol. 3), and use framework skew protection (chapter 24).

Cache invalidation

With immutable assets, the only thing that needs invalidating on deploy is the HTML (and any other non-hashed files: manifest.webmanifest, robots.txt, sw.js, /.well-known/*):

File Browser Cache-Control CDN On deploy
/assets/*.[hash].* public, max-age=31536000, immutable Cache 1 year Nothing: new names
index.html / SSR HTML no-cache (revalidate with ETag) Short TTL or invalidate Purge at the CDN
sw.js (service worker) no-cache (browsers also cap SW script caching) Short Purge; the SW update flow handles clients (chapter 29)
/api/* Per endpoint (chapter 19) Per endpoint Tag-based purges on data changes

CDN purges: by path (/index.html), by surrogate key or tag (Fastly, Cloudflare Enterprise, Akamai: purge everything tagged product-42 when that product changes), or purge-all (expensive and risky, since it causes an origin traffic spike called a "thundering herd"). Framework platforms (Vercel, Netlify) invalidate per deployment automatically. Service-worker caches are a second layer that must be versioned (chapter 29).

Environment configuration

Frontend configuration (API base URLs, feature flags, analytics keys, Sentry DSN) has a trap: build-time variables are baked into the bundle. import.meta.env.VITE_API_URL or process.env.NEXT_PUBLIC_* is replaced by a literal string at build time. Consequences:

  • You can't promote the same artifact from staging to production if config is baked in. Rebuilding per environment violates "build once, deploy many" (Part VII) and risks untested differences.
  • Never put secrets in client-side variables. Everything in the bundle is public. Prefixes like VITE_ and NEXT_PUBLIC_ exist precisely to make exposure explicit.

Patterns for runtime configuration (build once, configure per environment):

HTML
<!-- 1. Inject at serve time: the server/entrypoint writes config into the HTML -->
<script>window.__CONFIG__ = { apiUrl: "https://api.shop.example.com", sentryDsn: "…", features: { newCheckout: true } }</script>
<!-- (use a CSP nonce or hash for this inline script, chapter 28) -->
JavaScript
// 2. Fetch a config file at startup, generated per environment by the deploy pipeline or a ConfigMap
const config = await fetch("/config.json", { cache: "no-store" }).then(r => r.json());

// 3. SSR frameworks: read real environment variables on the server (process.env at run time),
//    and pass only the public subset to the client in props or a script tag.

For Angular, use an APP_INITIALIZER/provideAppInitializer that loads /assets/config.json before bootstrap. For Kubernetes, mount a ConfigMap as config.json into the Nginx container, or render it with an entrypoint script (envsubst). Feature flags (LaunchDarkly, Unleash, Flagsmith, OpenFeature-compatible) are runtime configuration with targeting. They decouple deploy from release, so code ships dark and turns on gradually.

Rollout and rollback

Ship safely:

  • Preview deployments per pull request (Vercel, Netlify and Cloudflare do this automatically, or build them in CI), so reviewers, designers and E2E tests can try the real build.
  • Progressive delivery: canary releases (send 5% of traffic to the new version, watch error rates and Web Vitals, then expand) or blue-green deployments, with feature flags for risky changes.
  • Automated smoke tests after deploy (Playwright against production, chapter 26), with automatic rollback on failure.
  • Fast rollback: keep previous versions deployable in one action (an immutable asset scheme, previous container images, platform "instant rollback").
  • Monitor the release (chapter 32): error rates, crash-free sessions, and Web Vitals per release version, compared with the previous one.

Lab: deploys that don't break open tabs

These experiments used a Node static server standing in for a host or CDN, two builds of a tiny SPA (v1 and v2, each with a hashed main script and a lazily imported orders chunk), and Chromium 153. Real hosts differ in configuration syntax, not in these behaviours.

Experiment 1: the SPA fallback, done naively and properly

Two server configurations. The naive one answers every unknown path with index.html; the proper one does that only for paths without a file extension:

Text
SPA fallback for everything:
  deep link /orders/42 → 200, app shows "app v1"
  missing /assets/missing-123.js → 200 text/html
fallback only for page routes:
  deep link /orders/42 → 200, app shows "app v1"
  missing /assets/missing-123.js → 404 text/plain

Both made deep links work. But the naive server answered a request for a missing JavaScript file with HTML and status 200, so browsers report a parse or MIME-type error instead of a 404, CDNs cache that HTML under the script's URL (it was a 200), and monitoring sees no errors. Hosts express the proper rule in their own way: Netlify's /* /index.html 200 redirect plus real 404s for assets, nginx's try_files $uri $uri/ /index.html scoped to page locations, Amazon CloudFront custom error responses (which apply to all 403/404s, so they need care), and framework adapters that know which routes exist.

Experiment 2: deploying while a user has the old version open

A user opens v1. Then v2 is deployed and v1's files are deleted. The user clicks Orders, which lazily imports v1's orders chunk:

Text
user opened: app v1
after deploying v2 and deleting v1's assets, user clicks Orders →
  ERROR: Failed to fetch dynamically imported module: http://localhost:8112/assets/orders-c93bc377.js
restore the file on the server and click again in the same tab →
  ERROR: Failed to fetch dynamically imported module: http://localhost:8112/assets/orders-c93bc377.js  (the failed import is remembered)

second user opened: app v1
deploy v2 but keep v1's hashed assets; user clicks Orders → orders page from v1
after a reload the user is on: app v2

Two lessons. First, the failure is permanent for that tab: browsers record a failed module fetch in the page's module map, so even after the file came back, the same import in the same tab failed again. Retrying the import doesn't help; only a reload does, which is why apps catch this error and prompt (or automatically reload once, guarding against loops). Second, keeping the old hashed files made the problem disappear: the second user's old page loaded its old chunk without trouble, and picked up v2 on the next reload. A deployment that only ever adds hashed files, and garbage-collects them weeks later, is the simplest robust design.

Experiment 3: how you switch releases matters

Twenty concurrent clients repeatedly loaded index.html and then the main script it named, for 1.5 seconds, while the server alternated between v1 and v2 twenty times, deployed three different ways:

Text
copy over the live folder, 20 deploys:                    { ok: 649,  broken: 229 }
switch a pointer between complete releases, 20 deploys:   { ok: 1785, broken: 141 }
switch the pointer and keep old hashed assets, 20 deploys: { ok: 2974, broken: 0 }
  • Copying over the live folder exposed half-finished states: an index.html from one version with the other version's assets, or no assets at all for a moment. About a quarter of page loads broke.
  • Switching a pointer (a symlink, a "current release" setting, a CDN origin path) removed the half-finished states, but loads still broke: a client fetched v1's index.html just before the switch and its script just after, and the script was gone from v2's directory.
  • Switching a pointer and keeping old hashed assets had zero broken loads across 2,974 page loads.

The real deploys of most static hosts (Vercel, Netlify, Cloudflare Pages) work like the third version: every deployment is immutable and stays addressable, and "deploying" moves the production alias. When you run your own S3-plus-CloudFront setup, you reproduce it by uploading new assets first, uploading index.html last, never deleting recent assets, and invalidating only the HTML paths in the CDN.

Try it yourself

  1. Add a global handler to your app that catches chunk-load failures (vite:preloadError in Vite, ChunkLoadError in webpack, or import() rejections) and offers a reload. Test it with experiment 2's setup.
  2. Configure a real host (Netlify, Cloudflare Pages, or nginx in a container) for an SPA so that deep links work and missing assets return 404. Verify both with curl -I.
  3. Deploy two versions to a host with preview URLs. Open the old one in a tab, promote the new one, and click around the old tab. Does anything break?
  4. Measure your production site's CDN cache hit ratio (most CDNs report it) and find the most-requested URLs that miss.

Revision sheet: frontend deployment

Key ideas

  • Static hosting: object storage + CDN, or a static platform; SPA fallback for page routes only; correct content types; HTTPS everywhere with HSTS.
  • Server-rendered hosting: long-running Node servers (containers, VMs), serverless functions, edge runtimes; their trade-offs in cold starts, limits, cost and distance to data.
  • Caching: hashed assets immutable for a year; HTML no-cache; Vary correctness; s-maxage and stale-while-revalidate for CDN-cached HTML; purge/invalidate HTML, never needed for hashed assets.
  • Releases: immutable, complete releases; atomic pointer switch; keep old hashed assets; handle chunk-load errors with a reload prompt; preview deployments per pull request.
  • Configuration: build once, promote everywhere; runtime config (/config.json, server-injected) over build-time baking; nothing in the client is secret.
  • Containers and proxies: multi-stage Docker builds (build in Node, serve with nginx or a minimal runtime); reverse proxies for TLS, compression, routing, rate limits and security headers.
  • Rollout and rollback: gradual percentage rollouts, canaries watched with error and Web Vitals metrics, feature flags, instant rollback by switching releases.

Numbers to remember

  • Lab: copying over the live folder broke about 26% of page loads during deploys; pointer switch with retained assets broke 0 of 2,974.
  • Light in fibre: about 200 km per ms; a far origin can add 100–200 ms per round trip that a nearby CDN location avoids.
  • max-age=31536000 = one year.

Pitfalls

  • Fallback returning HTML for missing assets (and CDNs caching it).
  • Deleting old assets on deploy; uploading index.html before its assets.
  • Long max-age on HTML; CDN caching of personalised or authenticated responses.
  • Secrets in frontend config; different builds per environment.
  • Service workers (chapter 29) pinning users to an old release with no update path.
  • No rollback plan or untested rollback.

Glossary

  • Origin: the server or bucket a CDN fetches from on a cache miss.
  • Cache hit ratio: the fraction of requests a CDN serves without contacting the origin.
  • Atomic deploy: switching from one complete release to another in a single step.
  • Preview deployment: a per-branch or per-PR deployment with its own URL.
  • Canary release: sending a small share of traffic to a new version first.
  • Edge runtime: a lightweight JavaScript runtime running at CDN locations.