Skip to content

Commit

Permalink
Apply headers from routeRules in the dev server.
Browse files Browse the repository at this point in the history
- These otherwise fail to be applied to public
  assets (see nitrojs#2749).
- This change replies them redundantly in the
  other cases (where they were already being
  applied), but the alternative would require
  duplicating or reversing the URL / file path
  logic from the "send" package.

fixes nitrojs#2749
  • Loading branch information
peterthenelson committed Oct 25, 2024
1 parent e3a2d6f commit 572d91f
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/core/dev-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { type FSWatcher, watch } from "chokidar";
import {
type H3Error,
type H3Event,
appendResponseHeaders,
createApp,
createError,
eventHandler,
Expand All @@ -22,15 +23,18 @@ import type {
Nitro,
NitroBuildInfo,
NitroDevServer,
NitroRouteRules,
NitroWorker,
} from "nitropack/types";
import { resolve } from "pathe";
import { debounce } from "perfect-debounce";
import { servePlaceholder } from "serve-placeholder";
import serveStatic from "serve-static";
import { joinURL } from "ufo";
import { joinURL, withoutBase } from "ufo";
import defaultErrorHandler from "./error";
import { createVFSHandler } from "./vfs";
import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
import defu from "defu";

function initWorker(filename: string): Promise<NitroWorker> | undefined {
if (!existsSync(filename)) {
Expand Down Expand Up @@ -166,6 +170,20 @@ export function createDevServer(nitro: Nitro): NitroDevServer {
// Debugging endpoint to view vfs
app.use("/_vfs", createVFSHandler(nitro));

// Apply headers based on routeRules. In cases where the dev server is being
// used, these would otherwise fail to be applied to public assets.
const routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: nitro.options.routeRules })
);
app.use("/", eventHandler((event) => {
const baseUrl = nitro.options.runtimeConfig.app.baseURL;
const normPath = withoutBase(event.path.split("?")[0], baseUrl);
const rules: NitroRouteRules = defu({}, ...routeRulesMatcher.matchAll(normPath).reverse());
if (rules.headers) {
appendResponseHeaders(event, rules.headers);
}
}));

// Serve asset dirs
for (const asset of nitro.options.publicAssets) {
const url = joinURL(
Expand Down

0 comments on commit 572d91f

Please sign in to comment.