← Back to React, page 7

react-0134 · Medium mid

How do you deploy a React single-page app, and what do the SPA fallback and cache headers have to do with it?

A client-rendered React app builds to static files that any static host or CDN can serve. Two server rules are essential. The server must return index.html for any route that is not a real file, otherwise deep links and page refreshes return 404. Hashed asset files should be cached for a long time as immutable, while index.html should not be cached, so users get new versions. Server-rendered apps need a Node or edge runtime instead.

Full answer

The build output of a Vite or similar SPA is a folder with index.html and hashed JavaScript, CSS and image files in an assets folder. Deployment means putting that folder behind a web server or CDN: Netlify, Vercel, Cloudflare Pages, GitHub Pages, S3 with CloudFront, or an Nginx server.

Rule 1: the SPA fallback. With client-side routing, a URL like /courses/react-basics exists only inside the app. If a user refreshes or opens that link, the server looks for a file named that path and finds nothing. The fix is a rewrite: for any path that is not a real file, return index.html with status 200, and let the router render the page. Hosts have a setting for it (Netlify _redirects with /* /index.html 200, Vercel rewrites, an Nginx try_files $uri /index.html). Requests for missing assets should still return 404 so that errors are visible. Your app should render its own not-found page for unknown routes.

Rule 2: cache headers. Build tools add a content hash to file names (app.3f9a1c.js). A changed file gets a new name, so old names can be cached for a year with Cache-Control: public, max-age=31536000, immutable. index.html refers to the current hashed files, so it must always be revalidated: Cache-Control: no-cache. Otherwise users get a stale HTML that points to files that may no longer exist after a deploy, a common source of "ChunkLoadError" bugs. Keep old assets available for a while after deploy, or handle chunk load errors by prompting a reload.

Other points:

  • Compression (gzip or Brotli) and HTTP/2 or HTTP/3, usually provided by the CDN.
  • Environment configuration is baked in at build time (see the Vite environment variable item), so build per environment or use runtime config.
  • Security headers (Content-Security-Policy, HSTS) and HTTPS.
  • Preview deployments for each pull request, and rollbacks by redeploying a previous build.
  • A base path if the app is served from a subfolder (base option in Vite and the router's basename).
  • Server-rendered apps (Next.js and similar) run on a Node server, serverless functions or edge runtime, and static parts go to the CDN.

The example is a small Node server with the fallback and cache rules, tested with real requests.

jsx
import http from 'node:http';

const files = {
  '/index.html': '<div id="root"></div><script src="/assets/app.3f9a1c.js"></script>',
  '/assets/app.3f9a1c.js': 'console.log("app")',
};

const server = http.createServer((request, response) => {
  const pathname = new URL(request.url, 'http://localhost').pathname;

  if (pathname.startsWith('/assets/')) {
    if (!files[pathname]) {
      response.writeHead(404);
      return response.end('not found');
    }
    response.writeHead(200, {
      'content-type': 'text/javascript',
      'cache-control': 'public, max-age=31536000, immutable',
    });
    return response.end(files[pathname]);
  }

  // SPA fallback: any other path gets index.html, and the router decides what to show.
  response.writeHead(200, { 'content-type': 'text/html', 'cache-control': 'no-cache' });
  response.end(files['/index.html']);
});

await new Promise((resolve) => server.listen(0, resolve));
const base = 'http://localhost:' + server.address().port;

for (const route of ['/', '/courses/react-basics', '/assets/app.3f9a1c.js', '/assets/missing.js']) {
  const res = await fetch(base + route);
  console.log(route + ' -> ' + res.status + ', cache-control: ' + (res.headers.get('cache-control') ?? 'none'));
}

server.close();

This ran a real HTTP server on a random local port and requested four paths with fetch. The deep link returns index.html with status 200, the hashed asset gets the long cache header, and a missing asset returns 404. Output of the run: / -> 200, cache-control: no-cache /courses/react-basics -> 200, cache-control: no-cache /assets/app.3f9a1c.js -> 200, cache-control: public, max-age=31536000, immutable /assets/missing.js -> 404, cache-control: none

Key points

  • A client-rendered build is static files that any static host or CDN can serve.
  • Return index.html for unknown non-asset routes, so deep links and refreshes work.
  • Cache hashed assets as immutable for a long time and revalidate index.html always.
  • Handle missing assets with 404 and show an in-app not-found page for unknown routes.
  • Plan for environment variables, a base path, security headers, previews and rollbacks.

Common mistakes

  • Forgetting the index.html fallback and getting 404 on refresh.
  • Caching index.html for a long time, so users stay on an old version.
  • Serving a missing asset as index.html with status 200, which hides errors.
  • Deleting old assets immediately after a deploy.
  • Setting the wrong base path for an app served from a subfolder.

Follow-ups

  • How would you handle a ChunkLoadError after a new deployment?
  • What changes when you deploy a server-rendered Next.js app?
  • How do preview deployments and rollbacks work on your platform?

Tips

  • Lead with the two rules: fallback and caching.
  • Explain why hashed names allow immutable caching.
  • Mention the stale index.html problem and chunk load errors.