From 5f06db1bf6ec745c29f2afc9853ca2ae904ee084 Mon Sep 17 00:00:00 2001 From: Gregor Becker Date: Tue, 24 Nov 2026 09:32:29 +0100 Subject: [PATCH] fix: stop serializing non-JSON bodies on the hook path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `compressStream()` wrapped every body in `new Response(body)`, which turns objects into `[object Object]` and arrays into `1,2` — so the Nuxt module with `encoding: 'stream'` sent broken JSON for `/server/api` routes. It now serializes JSON bodies (and sets the content type, like the buffered path), streams web / node streams, blobs, strings and bytes as they are, and leaves anything else alone. A node stream is only converted once it is actually compressed, so the uncompressed path never starts consuming it. The buffered path ran `JSON.stringify` on anything that wasn't a string or bytes, so a node stream returned from an h3 v1 handler was replaced by its internal state (`{"_events":…}`) and blobs / responses by `{}`. Only JSON-like values are serialized now; other bodies are skipped. --- src/helper.ts | 114 ++++++++++++++++++++++++----- test/body-types.test.ts | 158 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 253 insertions(+), 19 deletions(-) create mode 100644 test/body-types.test.ts diff --git a/src/helper.ts b/src/helper.ts index e71355d..daf59af 100644 --- a/src/helper.ts +++ b/src/helper.ts @@ -1,7 +1,7 @@ import { promisify } from 'node:util' import zlib from 'node:zlib' import { Buffer } from 'node:buffer' -import { Duplex } from 'node:stream' +import { Duplex, Readable } from 'node:stream' import process from 'node:process' import type { H3Event } from 'h3' import * as h3 from 'h3' @@ -280,11 +280,21 @@ function createCompressor(method: Compression): (payload: Uint8Array) => Promise return promisify(zlib[compressors[method]]) as (payload: Uint8Array) => Promise } -function isReadableStream(value: unknown): boolean { +function isReadableStream(value: unknown): value is ReadableStream { return typeof value === 'object' && value !== null && typeof (value as ReadableStream).getReader === 'function' } +function isNodeStream(value: unknown): value is Readable { + return typeof value === 'object' && value !== null + && typeof (value as Readable).pipe === 'function' + && typeof (value as Readable).on === 'function' +} + +function isBlob(value: unknown): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob +} + /** * Whether a hook response body carries no bytes at all. Empty bodies are never * compressed — the encoding framing would only add bytes, and a @@ -300,15 +310,47 @@ function isEmptyBody(body: unknown): boolean { return false } +/** + * Whether h3 would send a body as JSON: objects and arrays (e.g. returned from + * a `/server/api` route), numbers and booleans. Streams, `Blob`s, `Response`s + * and errors are not — serializing those would replace the payload with + * their internal state (`{"_events":…}`) or `{}`. + */ +function isJsonBody(body: unknown): boolean { + if (typeof body === 'number' || typeof body === 'boolean') + return true + + if (typeof body !== 'object' || body === null || body instanceof Error) + return false + + const value = body as Record + return typeof value.getReader !== 'function' + && typeof value.pipe !== 'function' + && typeof value.arrayBuffer !== 'function' +} + +/** + * Serializes a JSON body. `undefined` when it can't be (circular, or a value + * `JSON.stringify` drops). + */ +function serializeJson(body: unknown): string | undefined { + try { + return JSON.stringify(body) + } + catch { + return undefined + } +} + /** * Turns a response body into a buffer that can be compressed. Strings, buffers - * and typed arrays are used as-is; plain JSON-serializable values (e.g. objects - * returned from a `/server/api` route) are serialized to JSON and flagged so - * the caller can set the content type. Returns `undefined` for bodies that - * can't / shouldn't be buffered (streams, empty). + * and typed arrays are used as-is; JSON bodies (see {@link isJsonBody}) are + * serialized and flagged so the caller can set the content type. Returns + * `undefined` for bodies that can't / shouldn't be buffered (streams, blobs, + * responses, empty). */ function toCompressibleBuffer(body: unknown): { payload: Buffer; json: boolean } | undefined { - if (isEmptyBody(body) || isReadableStream(body)) + if (isEmptyBody(body)) return undefined if (typeof body === 'string') @@ -320,15 +362,41 @@ function toCompressibleBuffer(body: unknown): { payload: Buffer; json: boolean } if (body instanceof ArrayBuffer) return { payload: Buffer.from(body), json: false } - try { - const json = JSON.stringify(body) - if (json === undefined) - return undefined - return { payload: Buffer.from(json), json: true } - } - catch { + if (!isJsonBody(body)) return undefined - } + + const json = serializeJson(body) + return json === undefined ? undefined : { payload: Buffer.from(json), json: true } +} + +/** + * Prepares a response body for the stream path. Web and node streams, blobs, + * strings and bytes are streamed as they are; JSON bodies are serialized + * first (a plain `new Response(object)` would send `[object Object]`). + * Anything else — e.g. a `Response` returned on h3 v1 — is left alone. + * + * Streams are only opened once the body is actually compressed: `Readable.toWeb` + * starts consuming the node stream, so the "not compressed" path must not + * touch it. + */ +function toStreamSource(body: unknown): { open: () => ReadableStream; json: boolean } | undefined { + if (isEmptyBody(body)) + return undefined + + if (isReadableStream(body)) + return { open: () => body, json: false } + + if (isNodeStream(body)) + return { open: () => Readable.toWeb(body) as unknown as ReadableStream, json: false } + + if (typeof body === 'string' || body instanceof Uint8Array || body instanceof ArrayBuffer || isBlob(body)) + return { open: () => new Response(body as BodyInit).body as ReadableStream, json: false } + + if (!isJsonBody(body)) + return undefined + + const json = serializeJson(body) + return json === undefined ? undefined : { open: () => new Response(json).body as ReadableStream, json: true } } /** @@ -509,7 +577,8 @@ export async function compress( * * Nothing happens for empty or already-encoded bodies. Otherwise * `Vary: Accept-Encoding` is set, and the body is compressed if the client - * accepts the coding. + * accepts the coding. JSON bodies are serialized first, and web / node + * streams, blobs, strings and bytes are streamed as they are. * @param { H3Event } event - A H3 event object. * @param { Partial } response - A response object with body parameter. * @param { StreamCompression } [method] - The coding to apply, if the client accepts it. Negotiated from `Accept-Encoding` when omitted. @@ -522,7 +591,11 @@ export async function compressStream( method?: StreamCompression, options: StreamCompressionOptions = {}, ): Promise { - if (isEmptyBody(response.body) || isEncoded(event, response)) + if (isEncoded(event, response)) + return + + const source = toStreamSource(response.body) + if (!source) return varyOnAcceptEncoding(event, response) @@ -533,9 +606,12 @@ export async function compressStream( if (!encoding) return - const stream = new Response(response.body as string).body as ReadableStream + // Mirror h3, which serializes objects as JSON. + if (source.json) + setResponseHeader(event, 'Content-Type', 'application/json') + setEncoding(event, response, encoding) - response.body = stream.pipeThrough(createCompressionTransform(encoding)) + response.body = source.open().pipeThrough(createCompressionTransform(encoding)) } function ensureToResponse(): NonNullable { diff --git a/test/body-types.test.ts b/test/body-types.test.ts new file mode 100644 index 0000000..bd55db7 --- /dev/null +++ b/test/body-types.test.ts @@ -0,0 +1,158 @@ +import { Buffer } from 'node:buffer' +import { Readable } from 'node:stream' +import zlib from 'node:zlib' +import supertest from 'supertest' +import { describe, expect, it } from 'vitest' +import * as h3 from 'h3' +import { compress, compressStream, useCompression, useCompressionStream } from '../src' +import { applyCompression } from '../src/runtime/nitro-plugin' +import { isV1, isV2 } from './_version' + +// The hook path hands over whatever the handler returned. Only JSON-like +// values may be serialized; streams, blobs and responses must either be +// streamed as they are or left alone — never replaced by `[object Object]`, +// `1,2` or `{"_events":…}`. + +const { createApp, eventHandler, mockEvent, toNodeListener } = h3 as typeof import('h3') + +const json = { message: 'hello world', items: [1, 2, 3] } +const text = 'Hello world! '.repeat(50) + +async function readStream(stream: ReadableStream): Promise { + const chunks: Buffer[] = [] + const reader = stream.getReader() + while (true) { + const { done, value } = await reader.read() + if (done) + break + chunks.push(Buffer.from(value)) + } + return Buffer.concat(chunks) +} + +function eventFor(encoding = 'gzip') { + return mockEvent('/', { headers: { 'accept-encoding': encoding } }) +} + +describe.runIf(isV2)('stream path body types', () => { + it.each([ + ['an object', json], + ['an array', [1, 2, 3]], + ['a number', 42], + ])('serializes %s as JSON', async (_name, body) => { + const event = eventFor() + const response: { body: unknown } = { body } + + await useCompressionStream(event, response) + + expect(event.res.headers.get('content-encoding')).toEqual('gzip') + expect(event.res.headers.get('content-type')).toEqual('application/json') + expect(JSON.parse(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString())).toEqual(body) + }) + + it('streams a node stream', async () => { + const event = eventFor() + const response: { body: unknown } = { body: Readable.from([text.slice(0, 100), text.slice(100)]) } + + await useCompressionStream(event, response) + + expect(event.res.headers.get('content-encoding')).toEqual('gzip') + expect(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString()).toEqual(text) + }) + + it('streams a blob', async () => { + const event = eventFor() + const response: { body: unknown } = { body: new Blob([text]) } + + await useCompressionStream(event, response) + + expect(event.res.headers.get('content-encoding')).toEqual('gzip') + expect(zlib.gunzipSync(await readStream(response.body as ReadableStream)).toString()).toEqual(text) + }) + + it('does not touch a node stream it does not compress', async () => { + const event = eventFor('identity') + const stream = Readable.from([text]) + const response: { body: unknown } = { body: stream } + + await compressStream(event, response, 'gzip') + + expect(response.body).toBe(stream) + expect(stream.readableFlowing).toBeNull() + expect(event.res.headers.get('content-encoding')).toBeNull() + }) + + it('leaves a Response body alone', async () => { + const event = eventFor() + const body = new Response(text) + const response: { body: unknown } = { body } + + await useCompressionStream(event, response) + + expect(response.body).toBe(body) + expect(event.res.headers.get('content-encoding')).toBeNull() + }) +}) + +describe.runIf(isV2)('buffered path body types', () => { + it.each([ + ['a node stream', () => Readable.from([text])], + ['a web stream', () => new Response(text).body], + ['a blob', () => new Blob([text])], + ['a Response', () => new Response(text)], + ['an error', () => new Error('boom')], + ])('leaves %s alone instead of serializing it', async (_name, create) => { + const event = eventFor() + const body = create() + const response: { body: unknown } = { body } + + await useCompression(event, response) + + expect(response.body).toBe(body) + expect(event.res.headers.get('content-encoding')).toBeNull() + expect(event.res.headers.get('vary')).toBeNull() + }) + + it('still serializes JSON bodies', async () => { + const event = eventFor() + const response: { body: unknown } = { body: json } + + await compress(event, response) + + expect(event.res.headers.get('content-type')).toEqual('application/json') + expect(JSON.parse(zlib.gunzipSync(response.body as Buffer).toString())).toEqual(json) + }) +}) + +describe.runIf(isV1)('body types on the h3 v1 app hook', () => { + function appWith(hook: (event: any, response: any) => unknown) { + const app = createApp({ onBeforeResponse: hook }) + app.use('/api', eventHandler(() => json)) + app.use('/stream', eventHandler(() => Readable.from([text]))) + return supertest(toNodeListener(app)) + } + + it('the nuxt plugin in stream mode compresses a JSON api route', async () => { + const result = await appWith((event, response) => applyCompression(event, response, { encoding: 'stream' })) + .get('/api') + .set('Accept-Encoding', 'gzip') + + expect(result.headers['content-encoding']).toEqual('gzip') + expect(result.headers['content-type']).toContain('application/json') + expect(result.body).toEqual(json) + }) + + it('useCompression leaves a node stream intact', async () => { + const result = await appWith(useCompression).get('/stream').set('Accept-Encoding', 'gzip') + + expect(result.headers['content-encoding']).toBeUndefined() + expect(result.text).toEqual(text) + }) + + it('useCompressionStream compresses a node stream', async () => { + const result = await appWith(useCompressionStream).get('/stream').set('Accept-Encoding', 'gzip') + + expect(result.headers['content-encoding']).toEqual('gzip') + expect(result.text).toEqual(text) + }) +})