Skip to content
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
24 changes: 19 additions & 5 deletions src/utils/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,26 +112,40 @@ export function writeEarlyHints(
event: H3Event,
hints: Record<string, string | string[]>,
): void | Promise<void> {
const links = getEarlyHintLinks(hints);
if (links.length === 0) {
return;
}

// Use native early hints if available (Node.js)
if (event.runtime?.node?.res?.writeEarlyHints) {
return new Promise((resolve) => {
event.runtime?.node?.res?.writeEarlyHints(hints, () => resolve());
event.runtime?.node?.res?.writeEarlyHints(
{ link: links.length === 1 ? links[0]! : links },
() => resolve(),
);
});
}

// Fallback: Set Link headers for CDN support (only Link headers to avoid leaking sensitive headers)
for (const link of links) {
event.res.headers.append("link", link);
}
}

function getEarlyHintLinks(hints: Record<string, string | string[]>): string[] {
const links: string[] = [];
for (const [name, value] of Object.entries(hints)) {
if (name.toLowerCase() !== "link") {
continue;
}
if (Array.isArray(value)) {
for (const v of value) {
event.res.headers.append("link", v);
}
links.push(...value);
} else {
event.res.headers.append("link", value);
links.push(value);
}
}
return links;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,19 @@ describeMatrix("utils", (t, { it, describe, expect }) => {
});

describe("writeEarlyHints", () => {
it.skipIf(t.target !== "node")(
"resolves immediately when hints are empty on Node.js",
async () => {
t.app.get("/", async (event) => {
await writeEarlyHints(event, {});
return "ok";
});

const res = await t.fetch("/");
expect(await res.text()).toBe("ok");
},
);

// In Node.js, native writeEarlyHints sends 103 Early Hints status,
// so the Link header fallback is not used. Test fallback in web target only.
it.skipIf(t.target === "node")(
Expand Down