Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(dev): apply headers from route rules for static assets #2814

Open
wants to merge 7 commits into
base: v2
Choose a base branch
from
Open
Changes from 2 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
26 changes: 25 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,26 @@ 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(
"/",
pi0 marked this conversation as resolved.
Show resolved Hide resolved
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