import { defineEventHandler, getRequestURL, setResponseStatus } from 'h3'; import { resolveRoute } from '../../app/core/routes'; /** * Answers 404 for addresses this app does not serve. * * The status cannot be set from the catch-all page's `load`: Analog resolves * loaders through an internal request, so anything set on that response never * reaches the browser. Here it can be, and the route table is small enough to * state outright — the landing, plus the addresses records live at. */ const KNOWN_PATHS = new Set(['/', '/index.html']); const PASSTHROUGH_PREFIXES = ['/api/', '/_analog/', '/assets/', '/@', '/src/', '/node_modules/']; export default defineEventHandler((event) => { const { pathname } = getRequestURL(event); if (KNOWN_PATHS.has(pathname)) { return; } // Static files answer for themselves — a missing one is Nitro's 404, not a // page, and stamping this status on a hit would break the asset. if ( PASSTHROUGH_PREFIXES.some((prefix) => pathname.startsWith(prefix)) || /\.[a-z0-9]+$/i.test(pathname) ) { return; } // Shaped like a record's address (`/sobre-nosotros`, `/proyectos/x`, // `/en/team/x`). Only the API knows whether it exists, and asking it here // would be a second request for what the page asks anyway — so the page // sets the 404 itself when the API has nothing there. See `ui/page-shell.ts`. if (resolveRoute(pathname)) { return; } setResponseStatus(event, 404); });