Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `sendReactRouterResponse` corrupting binary response bodies whose content type is not in `binaryTypes` and dropping a leading byte order mark from text bodies
33 changes: 33 additions & 0 deletions packages/react-router-architect/__tests__/server-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,39 @@ describe("sendReactRouterResponse", () => {
expect(result.body).toMatch(image.toString("base64"));
});

it.each(["video/mp4", "image/x-icon", "Image/JPEG"])(
"handles resource routes with binary data sent as %s",
async (contentType) => {
let image = await fsp.readFile(path.join(__dirname, "554828.jpeg"));

let response = new Response(image, {
headers: { "content-type": contentType },
});

let result = await sendReactRouterResponse(response);

let body = Buffer.from(
result.body!,
result.isBase64Encoded ? "base64" : "utf8",
);
expect(body.equals(image)).toBe(true);
},
);

it.each([
["utf-8 text", "caf\u00e9 \ud83d\udc4b"],
["a byte order mark", "\ufeffname,city\nZo\u00eb,Kyiv\n"],
])("handles resource routes with %s", async (_, text) => {
let response = new Response(text, {
headers: { "content-type": "text/csv; charset=utf-8" },
});

let result = await sendReactRouterResponse(response);

expect(result.isBase64Encoded).toBe(false);
expect(result.body).toBe(text);
});

it("handles responses with immutable headers and cookies", async () => {
// Responses from fetch() have immutable headers
let server = http.createServer((_req, res) => {
Expand Down
10 changes: 9 additions & 1 deletion packages/react-router-architect/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,15 @@ export async function sendReactRouterResponse(
if (isBase64Encoded) {
body = await readableStreamToString(nodeResponse.body, "base64");
} else {
body = await nodeResponse.text();
// API Gateway reads unflagged bodies as UTF-8; send other bytes as base64
let bytes = Buffer.from(await nodeResponse.arrayBuffer());
let decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
try {
body = decoder.decode(bytes);
} catch {
body = bytes.toString("base64");
isBase64Encoded = true;
}
}
}

Expand Down