Deployed SPA Works Until Refresh: Fix Route 404s — Vibe Coding Clinic 2

Language: 한국어 · English

If in-app navigation works but refreshing or opening the same URL directly returns a 404, inspect the server before rewriting the router. A History API SPA needs its host to return the app’s index.html before the client router can read the URL.

This Vibe Coding Clinic answers one question: “Why does a deployed app open /notes/42 after a click, yet fail on refresh—and what is the smallest correct fix?”

1. Symptom: the home page and links work, but refresh fails

The home route / loads. Clicking Note 42 changes both the screen and the address to /notes/42. Refresh that page—or paste the same URL into a new tab—and the hosting platform serves its 404 page.

Those actions do not take the same path. An in-app click can be handled by JavaScript that is already running. A refresh, bookmark, or direct visit asks the server for a new document with GET /notes/42. If the server looks only for a matching file or server route, the request ends before the client router starts.

2. Set the boundary first: client route or server route?

A mobile-friendly diagnostic flow

  1. In-app navigation also fails → inspect the frontend route, base path, and build
  2. Clicks work; refresh alone returns 404 → inspect the host’s document fallback
  3. Only JavaScript or CSS returns 404 → inspect asset paths and build output
  4. Only /api/... returns 404 → inspect the deployed backend route
  5. The document is 200 but the screen is empty → inspect the client router, console, and base path

This article fixes only the second case. Turning every 404 into index.html can hide missing assets and broken APIs behind a misleading 200 response.

3. Minimal reproduction: a SPA that fails only on direct access

Create these two files in an empty folder. The example uses only built-in Node.js modules and synthetic routes.

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SPA refresh 404 diagnosis</title>
  <style>
    body { max-width: 42rem; margin: 3rem auto; padding: 0 1rem;
      font-family: system-ui, sans-serif; }
    nav { display: flex; gap: 1rem; flex-wrap: wrap; }
    a { color: #1456b8; }
    main { margin-top: 2rem; padding: 1rem;
      border: 1px solid #ccd3dd; border-radius: .75rem; }
  </style>
</head>
<body>
  <nav aria-label="Example routes">
    <a data-link href="/">Home</a>
    <a data-link href="/notes/42">Note 42</a>
  </nav>
  <main id="app" aria-live="polite"></main>

  <script>
    const routes = {
      '/': '<h1>Notes</h1><p>Select the synthetic note.</p>',
      '/notes/42': '<h1>Note 42</h1><p>This route exists only in the browser app.</p>'
    };

    function render() {
      document.querySelector('#app').innerHTML =
        routes[location.pathname] ?? '<h1>Not found in the app</h1>';
    }

    document.addEventListener('click', event => {
      const link = event.target.closest('a[data-link]');
      if (!link || event.button !== 0 || event.metaKey || event.ctrlKey ||
          event.shiftKey || event.altKey) return;

      const next = new URL(link.href);
      if (next.origin !== location.origin) return;

      event.preventDefault();
      history.pushState({}, '', next.pathname);
      render();
    });

    addEventListener('popstate', render);
    render();
  </script>
</body>
</html>

server.mjs

This teaching server serves the two entry documents and, with fallback enabled, the known client route /notes/42. Bare /api, its child paths, missing assets and unregistered routes remain 404. Match actual client-route ownership; an extensionless path is not automatically an application page.

import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';

const html = await readFile(new URL('./index.html', import.meta.url));
const useSpaFallback = process.argv.includes('--spa-fallback');
// Explicit teaching routes; do not infer API ownership from file extensions.
const clientRoutes = new Set(['/notes/42']);

createServer((request, response) => {
  const pathname = new URL(request.url ?? '/', 'http://127.0.0.1:4173').pathname;
  const isGetOrHead = request.method === 'GET' || request.method === 'HEAD';
  const wantsHtml = (request.headers.accept ?? '').includes('text/html');
  const isEntryDocument = pathname === '/' || pathname === '/index.html';
  const shouldServeApp = isGetOrHead && (
    isEntryDocument ||
    (useSpaFallback && wantsHtml && clientRoutes.has(pathname))
  );
  if (shouldServeApp) {
    response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
    response.end(request.method === 'HEAD' ? undefined : html);
    return;
  }
  response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
  response.end(request.method === 'HEAD' ? undefined : '404 Not Found');
}).listen(4173, '127.0.0.1', () => {
  console.log(`http://127.0.0.1:4173 (SPA fallback: ${useSpaFallback ? 'on' : 'off'})`);
});

Start with the fallback disabled:

node server.mjs
  1. Open http://127.0.0.1:4173 in a browser.
  2. Click Note 42. The screen changes and the URL becomes /notes/42.
  3. Refresh. The server has no file or server route at that path, so it returns 404 Not Found.

4. Diagnose from the first document request

① Identify the request type in Network

Open DevTools → Network and refresh /notes/42. If the failed request is a document with status 404, the failure likely sits at the server or hosting layer before JavaScript runs. If the failed resource is a script or stylesheet, investigate asset paths first.

② Compare soft and hard navigation

An in-app click can keep the current document and use history.pushState() to update the URL and view. A refresh, direct visit, or bookmark performs a hard navigation and requests a new document from the server. The fact that only one path fails is useful evidence.

③ Inspect the deployed output

Do not stop at a successful build message. Confirm that the deployed output directory contains the app shell, usually index.html, at the location the host expects. A fallback cannot serve a file that was never deployed.

④ Check fallback order and scope

Serve real static files and backend/API routes first. Only unmatched HTML document requests should fall back to index.html. On a hosted platform, the catch-all rewrite is usually the last routing rule.

5. Apply the smallest fix: enable a document fallback

Stop the example server with Ctrl+C, then restart it with the fallback enabled:

node server.mjs --spa-fallback

A direct request to /notes/42 now receives index.html. Once the browser runs the script, the app reads location.pathname and renders the matching note.

For this one-route exercise, a narrower mapping is sufficient. The host already serves index.html at /.

Netlify _redirects

/notes/42    /index.html    200

Vercel vercel.json

{"rewrites":[{"source":"/notes/42","destination":"/index.html"}]}

These are scoped teaching examples, not universal deployment recipes. Before expanding the match, identify the routes owned by the client router and preserve API and asset errors. Netlify documents that a broad /* fallback serves index.html instead of 404 for missing URLs; it therefore does not meet this article’s stricter missing-asset/API 404 requirement without additional routing decisions. An API exclusion on Vercel does not, by itself, protect missing assets either. Use framework-native routing for SSR, filesystem routes or server functions where required.

6. Verify success, failure, and retry

  • Success: opening /notes/42 in a new tab returns a 200 document with text/html, then renders Note 42.
  • Failure: if the document still returns 404, inspect the config file location, deployment output, and rule order.
  • False success: if /missing.js or /api/notes/42 returns your app shell with status 200, the fallback is too broad.
  • Retry: after correcting the config, test a new tab and a full refresh—not only another in-app click.

Use these checks against the minimal server:

curl -i -H 'Accept: text/html' http://127.0.0.1:4173/notes/42
curl -i http://127.0.0.1:4173/missing.js
curl -i -H 'Accept: text/html' http://127.0.0.1:4173/api
curl -i -H 'Accept: text/html' http://127.0.0.1:4173/api/notes/42
curl -i -H 'Accept: text/html' http://127.0.0.1:4173/does-not-exist

With fallback enabled, only the first request should return 200 HTML; the other four remain 404. With fallback disabled, /notes/42 also returns 404. Separately verify in-browser navigation, refresh and Back behavior.

7. Roll back

For the local example, stop the server and restart without --spa-fallback. On a host, remove only the rewrite you added and redeploy the previous configuration. Confirm that /notes/42 returns 404 again; a changed file is not proof that the rollback reached the serving environment.

8. A better prompt for your coding AI

The deployed app loads at / and its in-app link to /notes/42 works,
but a direct visit or refresh at that URL returns the host's 404 page.

Do not replace the framework or recreate routes before checking this boundary:
1. Classify the failed Network request as document, script, or API.
2. Explain the difference between client-side navigation and a new document request.
3. Verify the location of index.html in the actual build and deployed output.
4. Propose the smallest SPA fallback supported by the host's current official docs.
5. Keep static files and /api routes ahead of the catch-all.
   Do not turn missing.js or a bad API URL into 200 HTML.
6. End with checks for direct access, refresh, valid routes, genuine 404s,
   and an exact rollback procedure.

This prompt defines the failed boundary, constrains the repair, and names the errors that must remain visible. It makes a duplicated client route or an indiscriminate “return 200 for everything” patch less likely.

9. Common misdiagnoses

  1. “Add /notes/42 to the router again.” If an in-app click already renders it, the client route probably exists. Check whether the server fails before the app loads.
  2. “The build passed, so deployment routing is correct.” Build output and the directory a host actually serves can differ.
  3. “Rewrite every 404 to index.html.” That can hide a missing script or failed API behind HTML with a 200 status.
  4. “A 200 response means the page works.” The wrong HTML, a client error, or an unknown app route can still produce a blank screen or an in-app not-found view.
  5. “Hash routing is the only fix.” A hash avoids server path matching because the fragment is not sent to the server, but it changes the URL model. It is not the default repair when you can configure the host correctly.

10. When not to use this fix

Do not apply an SPA fallback by default to server-rendered routes, multi-page sites with real HTML files, backend/API endpoints, or genuinely missing static assets. If each route needs complete HTML for search or link previews, pre-rendering or SSR may be the better architecture. The symptom may look identical while ownership of the response is completely different.

Connect this Clinic to Sunday’s Fundamentals

This Clinic applies the boundary from “Frontend vs Backend vs Database: Where Does App Data Live? — Vibe Coding Lesson 2.” The frontend can know a client route while the server or host still has to answer the initial document request.

Official sources


RUDA DIRECTOR · 루다(이루다)

작성자·공개 작업·편집 기준 · 문의·정정 요청

다른 글 보기 · 주제 탐색