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 native fetch immutable headers issue #9693

Merged
merged 5 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/cyan-dingos-report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@remix-run/server-runtime": patch
---

Fix issue with setting additional headers on raw native fetch responses with immutable headers
29 changes: 29 additions & 0 deletions packages/remix-server-runtime/__tests__/server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,35 @@ describe("shared server runtime", () => {
expect(indexLoader.mock.calls.length).toBe(1);
});

test("data request calls loader returning raw fetch response", async () => {
let build = mockServerBuild({
root: {
default: {},
},
"routes/_index": {
parentId: "root",
index: true,
loader() {
return fetch(`https://remix.run/docs/en/main?_data=root`);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really want to keep this here but the only way to replicate this issue was to actually get a legit Response from a fetch call which is why we didn't run into this before. Thoughts on how to best prevent a regression in this area without spamming our prod server?

},
},
});
let handler = createRequestHandler(build, ServerMode.Development);

let request = new Request(`${baseUrl}/?_data=routes/_index`, {
method: "get",
});

let result = await handler(request);
expect(result.status).toBe(200);
expect(result.headers.get("X-Remix-Response")).toBe("yes");
expect(await result.json()).toEqual({
colorScheme: "system",
host: "remix.run",
isProductionHost: true,
noIndex: false,
});
});
test("data request calls loader and responds with generic message and error header", async () => {
let rootLoader = jest.fn(() => {
throw new Error("test");
Expand Down
55 changes: 50 additions & 5 deletions packages/remix-server-runtime/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,12 +360,12 @@ async function handleDataRequest(

// Mark all successful responses with a header so we can identify in-flight
// network errors that are missing this header
response.headers.set("X-Remix-Response", "yes");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this response is a direct undici fetch Response, then the headers are immutable and we can't change them. I didn't want to clone the response in 100% of scenarios since this isn't an issue with return json() and alternatives, so I am only cloning if this operation throws the immutable error

response = await safelySetHeader(response, "X-Remix-Response", "yes");
return response;
} catch (error: unknown) {
if (isResponse(error)) {
error.headers.set("X-Remix-Catch", "yes");
return error;
let response = await safelySetHeader(error, "X-Remix-Catch", "yes");
return response;
}

if (isRouteErrorResponse(error)) {
Expand Down Expand Up @@ -705,8 +705,8 @@ async function handleResourceRequest(
if (isResponse(error)) {
// Note: Not functionally required but ensures that our response headers
// match identically to what Remix returns
error.headers.set("X-Remix-Catch", "yes");
return error;
let response = await safelySetHeader(error, "X-Remix-Catch", "yes");
return response;
}

if (isResponseStub(error)) {
Expand Down Expand Up @@ -799,3 +799,48 @@ function createRemixRedirectResponse(
headers,
});
}

async function safelySetHeader(
response: Response,
name: string,
value: string
): Promise<Response> {
try {
response.headers.set(name, value);
} catch (error: unknown) {
// Check if this was a directly-returned native `fetch` response with
// immutable headers preventing us from setting additional headers
let isImmutableHeadersError =
isError(error) &&
error.name === "TypeError" &&
error.message === "immutable";

// Re-throw any other type of error
if (!isImmutableHeadersError) {
throw error;
}

// Clone the response so we can set our headers
let newHeaders = new Headers();
for (let [key, value] of response.headers.entries()) {
newHeaders.append(key, value);
}
newHeaders.set(name, value);
return new Response(await response.blob(), {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
return response;
}

function isError(e: unknown): e is Error {
return (
typeof e === "object" &&
e != null &&
"name" in e &&
"message" in e &&
"stack" in e
);
}