Skip to content

Commit a71f979

Browse files
committed
fix(http): tell compressed SSR bodies apart by mount order
The compressed-body check read Content-Encoding after the response finished. With compression() mounted before ssrMiddleware, the order the docs ask for, compression sets that header during writeHead, so every compressed render lost its render mode and the request detail and agent tool told the user to fix an order that was already right. Read the encoding when the headers go out, before compression's own header hook runs, and record it as compressedBeforeTrace. The panel and the agent tool key the compression note on that field.
1 parent e77d83d commit a71f979

8 files changed

Lines changed: 54 additions & 13 deletions

File tree

‎app/src/pages/network-inspector.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ interface SsrRequest {
8888
headers: Record<string, string>;
8989
navigations?: SsrNavigation[];
9090
overrides?: { id: string; kind: SsrOverrideKind; applied: boolean; note?: string }[];
91+
compressedBeforeTrace?: boolean;
9192
aborted?: boolean;
9293
}
9394

@@ -2373,8 +2374,9 @@ export class NetworkInspector {
23732374

23742375
/** The response encoding when a compression middleware ran before `ssrMiddleware` saw the body. */
23752376
compressedWith(req: SsrRequest): string | undefined {
2376-
const encoding = req.headers['content-encoding'];
2377-
return encoding && encoding.toLowerCase() !== 'identity' ? encoding : undefined;
2377+
// The final Content-Encoding is also set when compression runs after ssrMiddleware, as it should.
2378+
if (!req.compressedBeforeTrace) return undefined;
2379+
return req.headers['content-encoding'] ?? 'unknown encoding';
23782380
}
23792381

23802382
renderModeLabel(mode: SsrRequest['renderMode']): string {

extension/ui/assets/browser-agent-rpc-BXhoSh1z-CZbRQcfu.js renamed to extension/ui/assets/browser-agent-rpc-BXhoSh1z-wXf_92mg.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extension/ui/index.html‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/devtools/src/__tests__/ssr-overrides.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ describe('ssrMiddleware overrides', () => {
242242
expect(res.body).toBe(gzipped.toString());
243243
expect(recorded[0]).toMatchObject({
244244
renderMode: 'unknown',
245+
compressedBeforeTrace: true,
245246
headers: { 'content-encoding': 'gzip' },
246247
overrides: [
247248
{ kind: 'state-edit', applied: false, note: expect.stringContaining('after compression') },
@@ -251,6 +252,34 @@ describe('ssrMiddleware overrides', () => {
251252
expect(text).toContain('mount `ssrMiddleware` after');
252253
});
253254

255+
it('reads and edits the HTML when compression() is mounted before the middleware', () => {
256+
ssrRegistry().overrides = [override({ kind: 'state-edit', key: 'a', value: '{"b":2}' })];
257+
const res = new FakeResponse();
258+
// Like compression(): its header is set during writeHead, and the body is encoded on the way out.
259+
const writeHead = res.writeHead;
260+
res.writeHead = function (this: FakeResponse, ...args: Parameters<FakeResponse['writeHead']>) {
261+
this.setHeader('content-encoding', 'gzip');
262+
return writeHead.apply(this, args);
263+
};
264+
const end = res.end;
265+
res.end = function (this: FakeResponse, chunk?: string | Buffer) {
266+
if (!this.headersSent) this.writeHead(this.statusCode);
267+
return end.call(this, chunk === undefined ? chunk : gzipSync(chunk));
268+
};
269+
createSsrMiddleware()(request(), res as unknown as ServerResponse, () => {});
270+
res.setHeader('content-type', 'text/html');
271+
res.end(STATE_HTML);
272+
expect(res.sentHeaders['content-encoding']).toBe('gzip');
273+
expect(recorded[0]).toMatchObject({
274+
renderMode: 'server',
275+
headers: { 'content-encoding': 'gzip' },
276+
overrides: [{ kind: 'state-edit', applied: true, note: 'set a' }],
277+
});
278+
expect(recorded[0].compressedBeforeTrace).toBeUndefined();
279+
const text = explainSsrRequestText([sanitizeSsrRequest(recorded[0])!], [], [], {});
280+
expect(text).not.toContain('already compressed');
281+
});
282+
254283
it('rewrites the TransferState script before the response is sent', () => {
255284
ssrRegistry().overrides = [override({ kind: 'state-edit', key: 'a', value: '{"b":2}' })];
256285
const res = new FakeResponse();

‎packages/devtools/src/rpc/ssr-tools.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ export function sanitizeSsrRequest(raw: unknown): SsrRequest | undefined {
139139
headers,
140140
...(navigations.length ? { navigations } : {}),
141141
...(overrides.length ? { overrides } : {}),
142+
...(r.compressedBeforeTrace === true ? { compressedBeforeTrace: true } : {}),
142143
...(r.aborted === true ? { aborted: true } : {}),
143144
};
144145
}
@@ -273,8 +274,9 @@ export function explainSsrRequestText(
273274
`- Render (arrival to headers): ${ms(r.renderMs)}; total ${ms(r.durationMs)}; ${size(r.bytes)} sent`,
274275
`- Server HttpClient calls: ${r.fetches}, ${ms(r.fetchMs)} in total`,
275276
];
276-
const encoding = r.headers['content-encoding'];
277-
if (encoding && encoding.toLowerCase() !== 'identity') {
277+
// The final Content-Encoding is also set when compression runs after ssrMiddleware, as it should.
278+
if (r.compressedBeforeTrace) {
279+
const encoding = r.headers['content-encoding'] ?? 'unknown encoding';
278280
lines.push(
279281
`- The body was already compressed (${code(encoding)}) when \`ssrMiddleware\` saw it, so the render mode can't be read and TransferState edits can't apply. In \`server.ts\`, mount \`ssrMiddleware\` after \`compression()\`.`,
280282
);

‎packages/devtools/src/ssr-middleware.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,15 @@ export function createSsrMiddleware(options: SsrMiddlewareOptions = {}) {
112112
let bytes = 0;
113113
let sniff = '';
114114
let done = false;
115+
// Whether the body was encoded before it reached this middleware, read when the headers go
116+
// out. A compression() mounted before this one sets its header inside that writeHead call, so
117+
// its later `Content-Encoding` does not count; one mounted after has already set it.
118+
let encodedAtHead: boolean | undefined;
119+
const bodyEncoded = () => encodedAtHead ?? encoded(res);
115120

116121
const writeHead = res.writeHead;
117122
res.writeHead = function (this: ServerResponse, ...args: unknown[]) {
123+
encodedAtHead ??= encoded(res);
118124
if (!renderMs) {
119125
renderMs = Date.now() - at;
120126
const timing = [
@@ -218,7 +224,7 @@ export function createSsrMiddleware(options: SsrMiddlewareOptions = {}) {
218224
const isHtml = /\btext\/html\b/.test(headerText(res.getHeader('content-type')) ?? '');
219225
// A compression middleware that wraps res.write outside this one hands over encoded
220226
// bytes, where the TransferState script can't be found. They are sent as they are.
221-
const compressed = isHtml && encoded(res);
227+
const compressed = isHtml && bodyEncoded();
222228
const html = compressed ? '' : body.toString('utf8');
223229
const hasState = isHtml && /<script\b[^>]*\sid="[^"]*-state"/.test(html);
224230
const edited = hasState ? editTransferState(html, list) : null;
@@ -269,6 +275,8 @@ export function createSsrMiddleware(options: SsrMiddlewareOptions = {}) {
269275
const type = headerText(res.getHeader('content-type')) ?? '';
270276
// Static files and API answers that reach this far are not renders.
271277
if (!aborted && !/\btext\/html\b/.test(type) && res.statusCode < 300) return;
278+
const isHtml = /\btext\/html\b/.test(type);
279+
const compressed = isHtml && bodyEncoded();
272280
const headers: Record<string, string> = {};
273281
for (const name of KEPT_HEADERS) {
274282
const value = headerText(res.getHeader(name));
@@ -284,15 +292,13 @@ export function createSsrMiddleware(options: SsrMiddlewareOptions = {}) {
284292
renderMs: renderMs || Date.now() - at,
285293
bytes,
286294
// Encoded bytes are not HTML, so only the status is read then.
287-
renderMode: renderModeOf(
288-
/\btext\/html\b/.test(type) && !encoded(res) ? sniff : '',
289-
res.statusCode,
290-
),
295+
renderMode: renderModeOf(isHtml && !compressed ? sniff : '', res.statusCode),
291296
fetches: active.fetches,
292297
fetchMs: active.fetchMs,
293298
headers,
294299
...(active.navigations?.length ? { navigations: active.navigations } : {}),
295300
...(active.overrides?.length ? { overrides: active.overrides } : {}),
301+
...(compressed ? { compressedBeforeTrace: true } : {}),
296302
...(aborted ? { aborted: true } : {}),
297303
};
298304
registry.record?.(request);

‎packages/devtools/src/ssr-registry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ export interface SsrRequest {
4040
navigations?: SsrNavigation[];
4141
/** SSR overrides from the panel that matched this request. */
4242
overrides?: AppliedOverride[];
43+
/** The body was already compressed when `ssrMiddleware` saw it, because compression ran first. */
44+
compressedBeforeTrace?: boolean;
4345
/** The connection closed before the response finished. */
4446
aborted?: boolean;
4547
}

0 commit comments

Comments
 (0)