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
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
32 changes: 31 additions & 1 deletion src/core/dev-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
Nitro,
NitroBuildInfo,
NitroDevServer,
NitroRouteRules,
NitroWorker,
} from "nitropack/types";
import { resolve } from "pathe";
Expand All @@ -31,6 +32,8 @@ import serveStatic from "serve-static";
import { joinURL } 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,13 +169,40 @@ 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 })
);
// Serve asset dirs
for (const asset of nitro.options.publicAssets) {
const url = joinURL(
nitro.options.runtimeConfig.app.baseURL,
asset.baseURL || "/"
);
app.use(url, fromNodeMiddleware(serveStatic(asset.dir)));
app.use(
url,
fromNodeMiddleware(
serveStatic(asset.dir, {
setHeaders: (res) => {
const path = res.req.url;
if (path === undefined) {
return;
}
const rules: NitroRouteRules = defu(
{},
...routeRulesMatcher.matchAll(path).reverse()
);
if (!rules.headers) {
return;
}
for (const [k, v] of Object.entries(rules.headers)) {
res.appendHeader(k, v);
}
},
})
)
);
if (!asset.fallthrough) {
app.use(url, fromNodeMiddleware(servePlaceholder()));
}
Expand Down
1 change: 1 addition & 0 deletions test/fixture/nitro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export default defineNitroConfig({
"/rules/_/cached/noncached": { cache: false, swr: false, isr: false },
"/rules/_/cached/**": { swr: true },
"/api/proxy/**": { proxy: "/api/echo" },
"/build/**": { headers: { "x-build-header": "works" } },
},
prerender: {
crawlLinks: true,
Expand Down
27 changes: 14 additions & 13 deletions test/presets/netlify-legacy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,20 @@ describe("nitro:preset:netlify-legacy", async () => {
);

expect(headers).toMatchInlineSnapshot(`
"/rules/headers
cache-control: s-maxage=60
/rules/cors
access-control-allow-origin: *
access-control-allow-methods: GET
access-control-allow-headers: *
access-control-max-age: 0
/rules/nested/*
x-test: test
/build/*
cache-control: public, max-age=3600, immutable
"
`);
"/rules/headers
cache-control: s-maxage=60
/rules/cors
access-control-allow-origin: *
access-control-allow-methods: GET
access-control-allow-headers: *
access-control-max-age: 0
/rules/nested/*
x-test: test
/build/*
cache-control: public, max-age=3600, immutable
x-build-header: works
"
`);
});
it("should write config.json", async () => {
const config = await fsp
Expand Down
27 changes: 14 additions & 13 deletions test/presets/netlify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,20 @@ describe("nitro:preset:netlify", async () => {
);

expect(headers).toMatchInlineSnapshot(`
"/rules/headers
cache-control: s-maxage=60
/rules/cors
access-control-allow-origin: *
access-control-allow-methods: GET
access-control-allow-headers: *
access-control-max-age: 0
/rules/nested/*
x-test: test
/build/*
cache-control: public, max-age=3600, immutable
"
`);
"/rules/headers
cache-control: s-maxage=60
/rules/cors
access-control-allow-origin: *
access-control-allow-methods: GET
access-control-allow-headers: *
access-control-max-age: 0
/rules/nested/*
x-test: test
/build/*
cache-control: public, max-age=3600, immutable
x-build-header: works
"
`);
});

it("writes config.json", async () => {
Expand Down
16 changes: 16 additions & 0 deletions test/presets/nitro-dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@
expect(data.keys).includes("src:nitro.config.ts");
});

it("static asset headers", async () => {
const { headers } = await ctx.fetch("/build/test.txt");
expect(Object.fromEntries(headers)).toMatchObject({

Check failure on line 33 in test/presets/nitro-dev.test.ts

View workflow job for this annotation

GitHub Actions / ci (ubuntu-latest)

test/presets/nitro-dev.test.ts > nitro:preset:nitro-dev > static asset headers

AssertionError: expected { 'accept-ranges': 'bytes', …(8) } to match object { 'accept-ranges': 'bytes', …(9) } - Expected + Received Object { "accept-ranges": "bytes", "cache-control": "public, max-age=0", "connection": "keep-alive", "content-length": "7", "content-type": "text/plain; charset=UTF-8", "date": Any<String>, - "etag": "W/\"7-18df5a508c5\"", + "etag": "W/\"7-19308a09666\"", "keep-alive": "timeout=5", "last-modified": Any<String>, - "x-build-header": "works", } ❯ test/presets/nitro-dev.test.ts:33:45
"accept-ranges": "bytes",
"cache-control": "public, max-age=0",
"last-modified": expect.any(String),
etag: 'W/"7-18df5a508c5"',
"content-type": "text/plain; charset=UTF-8",
"content-length": "7",
date: expect.any(String),
connection: "keep-alive",
"keep-alive": "timeout=5",
"x-build-header": "works",
});
});

describe("openAPI", () => {
let spec: OpenAPI3;
it("/_openapi.json", async () => {
Expand Down
1 change: 1 addition & 0 deletions test/presets/vercel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ describe("nitro:preset:vercel", async () => {
{
"headers": {
"cache-control": "public, max-age=3600, immutable",
"x-build-header": "works",
},
"src": "/build/(.*)",
},
Expand Down
Loading