Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 54 additions & 28 deletions src/build/vite/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,39 +242,65 @@ export async function configureViteDevServer(ctx: NitroPluginContext, server: Vi
// Handle server routes first to avoid conflicts with static assets served by Vite from the root
// https://github.com/vitejs/vite/pull/20866
server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
const fetchDest = req.headers["sec-fetch-dest"];
const accept = req.headers["accept"];
const ext = req.url!.split(/[?#]/, 1)[0].match(/\.([a-z0-9]+)$/i)?.[1];
const isNitroRoute = !!nitro.routing.routes.match(
// Vite-internal prefixes (/@vite/client, /__vue-router/auto-routes, ...) are never Nitro's.
if (/^\/(?:__|@)/.test(req.url!)) {
return next();
}

// `nitro.routing.routes` always includes the SSR catch-all `/**` in SSR apps, so an explicit
// user route must be told apart from the catch-all. A root-level user catch-all
// (`routes/[...].ts` -> `/**`, `routes/[...slug].ts` -> `/**:slug`) is as authoritative as the
// SSR `/**` and must not swallow Vite asset serves either, so both forms count as catch-all;
// prefixed splat routes (`/api/photos/**`) are deterministic user routes and stay explicit.
const match = nitro.routing.routes.match(
req.method || "",
new URL(withBase(req.url!, nitro.options.baseURL), "http://localhost").pathname
);
// Sec-Fetch-* is only sent on "potentially trustworthy" origins, so on plain-HTTP non-loopback (e.g. http://10.0.0.x) it's absent and a splat Nitro route may swallow browser asset loads (#4234). When the header is missing, treat known asset extensions without `text/html` in Accept as asset loads and let Vite handle them.
const isAssetByDest =
typeof fetchDest === "string" && !/^(document|iframe|frame|empty)$/.test(fetchDest);
const isAssetByExt = !!ext && ASSET_EXT_RE.test(ext);
const acceptsHTML = typeof accept === "string" && /\btext\/html\b/.test(accept);
const treatAsAsset = isAssetByDest || (!fetchDest && isAssetByExt && !acceptsHTML);
const matchedHandlers = match ? (Array.isArray(match) ? match : [match]) : [];
const isExplicitRoute = matchedHandlers.some(
(h) => h?.route && h.route !== "/**" && !h.route.startsWith("/**:")
);

// An explicit user route is a deterministic match and always wins, regardless of how the
// browser tags the request (#4108, #4241, #4252, #4270) — no heuristic may override it.
if (isExplicitRoute) {
return nitroDevMiddleware(req, res, next);
}

// Otherwise the request is unmatched or matched only by the SSR catch-all `/**` — genuinely
// ambiguous between a page navigation (-> Nitro) and an asset load (-> Vite). A wrong guess
// here only affects the catch-all fallback, never an explicit route.
res.setHeader("vary", "sec-fetch-dest, accept");
// An explicit Nitro route reaches Nitro even when the request is tagged as an asset (e.g. `<img src="/api/image">` with `sec-fetch-dest: image`, #4241), UNLESS the URL also has an asset-like extension — in that case Vite stays the definitive handler so a splat doesn't swallow `<script src=".../entry-client.ts">` (#4234).
const nitroWins = isNitroRoute && !(isAssetByExt && treatAsAsset);
// Fallback for unknown URLs: extensionless, non-asset requests default to Nitro (page navigation, SSR catch-all).
const documentFallback = !ext && !treatAsAsset;
const routeToNitro =
(nitroWins || documentFallback) &&
// Special prefixes (/__vue-router/auto-routes, /@vite-plugin-layouts/, etc)
!/^\/(?:__|@)/.test(req.url!);
if (routeToNitro) {
nitroDevMiddleware(req, res, next);
} else {
if (treatAsAsset) {
// This is an asset load — Vite is the definitive handler. Mark the
// request so the catch-all `nitroDevMiddleware` registered after Vite
// doesn't fall back into a splat Nitro route on a 404.
(req as IncomingMessage & { _nitroHandled?: boolean })._nitroHandled = true;
}
next();
const fetchDest = req.headers["sec-fetch-dest"];
const ext = req.url!.split(/[?#]/, 1)[0].match(/\.([a-z0-9]+)$/i)?.[1];

// A known asset extension without `text/html` in `Accept` — the fallback signal when
// `Sec-Fetch-Dest` is unavailable. The header is absent on plain-HTTP non-loopback origins
// (e.g. http://10.0.0.x, #4234), and `empty` (fetch/XHR) is ambiguous: it tags both API
// calls and `fetch()`ed assets, so it falls back to the extension like a missing header.
const isAssetByExt =
!!ext && ASSET_EXT_RE.test(ext) && !/\btext\/html\b/.test(req.headers["accept"] || "");

// `document`/`iframe`/`frame` are definite navigations; any other concrete `Sec-Fetch-Dest`
// (`image`, `video`, `style`, ...) is a definite asset load.
const isAsset =
typeof fetchDest === "string" && fetchDest !== "empty"
? !/^(?:document|iframe|frame)$/.test(fetchDest)
: isAssetByExt;

// Non-asset requests go to Nitro: the catch-all (`matchedHandlers` are all catch-all here,
// since explicit routes already returned) renders them, and bare (extensionless) unmatched
// URLs default to Nitro as page navigations.
if (!isAsset && (matchedHandlers.length > 0 || !ext)) {
return nitroDevMiddleware(req, res, next);
}

if (isAsset) {
// Vite is the definitive handler — mark the request so the catch-all `nitroDevMiddleware`
// registered after Vite doesn't fall back into a splat Nitro route on a 404.
(req as IncomingMessage & { _nitroHandled?: boolean })._nitroHandled = true;
}
next();
});

return () => {
Expand Down
42 changes: 42 additions & 0 deletions test/vite/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,46 @@ describe("vite:app", () => {
const value = await res.text();
expect(value).toBe("value-from-ssr");
});

// #4234: a request matching only the SSR `/**` catch-all (no explicit route) that looks like
// an asset must be handled by Vite, not swallowed by the catch-all renderer.
test("does not let the SSR catch-all swallow asset-tagged requests", async () => {
const res = await fetch(`${serverURL}/missing-asset.css`, {
headers: { "sec-fetch-dest": "style" },
redirect: "manual",
});
// The SSR renderer would answer 200 with JSON; Vite 404s a missing asset.
expect(res.status).not.toBe(200);
});

// #4234: with `Sec-Fetch-*` absent (plain-HTTP non-loopback origins), a known asset extension
// is the only signal — such a catch-all-only request must still reach Vite, not the renderer.
test("does not let the SSR catch-all swallow asset loads when sec-fetch-dest is absent", async () => {
const res = await fetch(`${serverURL}/missing-asset.js`, {
headers: { accept: "*/*" },
redirect: "manual",
});
expect(res.status).not.toBe(200);
});

// `Sec-Fetch-Dest: empty` (fetch/XHR) is ambiguous: a `fetch()`ed asset matching only the SSR
// `/**` catch-all must reach Vite via the extension heuristic, not be swallowed by the renderer.
test("does not let the SSR catch-all swallow fetch()ed assets (sec-fetch-dest: empty)", async () => {
const res = await fetch(`${serverURL}/missing-asset.css`, {
headers: { "sec-fetch-dest": "empty" },
redirect: "manual",
});
expect(res.status).not.toBe(200);
});

// A page navigation matching only the SSR `/**` catch-all must reach the renderer.
test("routes page navigations to the SSR catch-all renderer", async () => {
const res = await fetch(`${serverURL}/some/nested/page`, {
headers: { "sec-fetch-dest": "document", accept: "text/html" },
redirect: "manual",
});
expect(res.status).toBe(200);
const data = (await res.json()) as { config: string };
expect(data.config).toBe("NITRO_");
});
});
29 changes: 25 additions & 4 deletions test/vite/baseurl-dotted-param.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,34 @@ describe("vite:baseURL dotted params", { sequential: true }, () => {
expect(await response.text()).toBe("image");
});

// Browsers omit Sec-Fetch-* on plain-HTTP non-loopback origins (e.g. http://10.0.0.x:3000). Without that signal, a splat Nitro route would swallow `<script src=".../entry-client.ts">` requests. Accept + asset extension is used as a fallback to keep asset loads routed to Vite.
test("does not misroute asset loads to splat Nitro routes when sec-fetch-dest is absent", async () => {
const response = await fetch(`${serverURL}/subdir/api/proxy/entry-client.ts`, {
// #4234: a `.ts`/asset URL that matches no Nitro route must be handled by Vite, not diverted to Nitro. Browsers omit Sec-Fetch-* on plain-HTTP non-loopback origins, so the asset extension is the only signal.
test("does not misroute unmatched asset loads to Nitro when sec-fetch-dest is absent", async () => {
const response = await fetch(`${serverURL}/subdir/src/entry-client.ts`, {
headers: { accept: "*/*" },
redirect: "manual",
});
expect(await response.text()).not.toBe("entry-client.ts");
expect(response.status).not.toBe(200);
expect(await response.text()).not.toContain("fixture");
});

// #4252: an explicit Nitro route whose URL ends in an asset-like extension (`.jpg`) must still reach the route handler instead of being misrouted to Vite's static middleware.
test("routes URLs with asset-like extensions to an explicit Nitro route", async () => {
const response = await fetch(`${serverURL}/subdir/api/proxy/12345.jpg`, {
headers: { accept: "*/*" },
redirect: "manual",
});
expect(response.status).toBe(200);
expect(await response.text()).toBe("12345.jpg");
});

// #4270: an asset `Sec-Fetch-Dest` (e.g. `video`) must not divert an explicit Nitro route to Vite, even when the URL also has an asset-like extension.
test("routes asset-tagged requests to an explicit Nitro route", async () => {
const response = await fetch(`${serverURL}/subdir/api/proxy/clip.mp4`, {
headers: { "sec-fetch-dest": "video" },
redirect: "manual",
});
expect(response.status).toBe(200);
expect(await response.text()).toBe("clip.mp4");
});

// The extension extraction must look at the path only — a `.png` in the query string (e.g. `?file=bar.png`) must not flag the request as an asset and divert it to Vite.
Expand Down
1 change: 1 addition & 0 deletions test/vite/root-wildcard-fixture/routes/[...path].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default (event: any) => "root-wildcard:" + (event.context.params?.path ?? "");
11 changes: 11 additions & 0 deletions test/vite/root-wildcard-fixture/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from "vite";
import { nitro } from "nitro/vite";

export default defineConfig({
plugins: [
nitro({
serverDir: "./",
serveStatic: false,
}),
],
});
66 changes: 66 additions & 0 deletions test/vite/root-wildcard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { fileURLToPath } from "node:url";
import type { ViteDevServer } from "vite";
import { beforeAll, afterAll, describe, expect, test } from "vitest";

const { createServer } = (await import(
process.env.NITRO_VITE_PKG || "vite"
)) as typeof import("vite");

describe("vite:root wildcard routes", { sequential: true }, () => {
let server: ViteDevServer;
let serverURL: string;

const rootDir = fileURLToPath(new URL("./root-wildcard-fixture", import.meta.url));
const originalCwd = process.cwd();

beforeAll(async () => {
process.chdir(rootDir);
server = await createServer({ root: rootDir });
await server.listen("0" as unknown as number);
const addr = server.httpServer?.address() as {
port: number;
address: string;
family: string;
};
serverURL = `http://${addr.family === "IPv6" ? `[${addr.address}]` : addr.address}:${addr.port}`;
}, 30_000);

afterAll(async () => {
await server?.close();
process.chdir(originalCwd);
});

// #4234/#4266: a root-level user catch-all (`routes/[...path].ts` -> `/**:path`) is as
// authoritative as the SSR `/**` renderer — it must not swallow Vite's own asset serves
// (`<script src=".../entry-client.ts">`), so the asset heuristic still applies to it.
test("root-level named catch-all does not swallow Vite asset loads", async () => {
for (const fetchDest of ["script", "style", "image", undefined]) {
const headers: Record<string, string> = { accept: "*/*" };
if (fetchDest) {
headers["sec-fetch-dest"] = fetchDest;
}
const response = await fetch(`${serverURL}/entry-client.ts`, {
headers,
redirect: "manual",
});
// The catch-all would answer 200 (`root-wildcard:...`); Vite 404s a missing asset.
expect(response.status, `sec-fetch-dest: ${fetchDest}`).not.toBe(200);
}
});

// A non-asset page navigation must still reach the root catch-all handler.
test("root-level named catch-all handles page navigations", async () => {
const headerVariants: Record<string, string>[] = [
{},
{ "sec-fetch-dest": "document", accept: "text/html" },
];
for (const headers of headerVariants) {
const response = await fetch(`${serverURL}/some/nested/page`, {
headers,
redirect: "manual",
});
expect(response.status).toBe(200);
expect(await response.text()).toBe("root-wildcard:some/nested/page");
}
});
});
Loading