Skip to content
Myr

feat(request): add cloneRawRequest utility for request cloning (#4382)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

**Problem** After using Hono validators, the `raw` Request obejct gets consumed during body parsing, making it unusable for external libraries like `better-auth`. This results in the error: ```shell TypeError: Cannot construct a Request with a Request object that has already been used. ``` **Root Cause** The issue occurs in the `#cachedBody` method in `HonoRequest`. When parsing request bodies (json, text, etc.), the method directly calls parsing methods on the raw Request object, which consumes its body stream. Once consumed, the Request cannot be cloned or reused by external libraries. **Solution** Adding a utility function to clone HonoRequest's underlying raw Request object, handling both consumed and unconsumed request bodies.

authored by Kamaal Farah · committed by GitHub · parent fb2a7ef · Browse files · 3 files+263 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Kamaal Farah <kamaal.f1@gmail.com>

Diff stats

3 files+263 added−1 removed

  • tests:+195 added−1 removed
  • other:+68 added−0 removed

3 files+263 added−1 removed

modified:src/validator/validator.test.ts+70 added
2 unmodified lines
3import { z } from 'zod'4import type { Context } from '../context'5import { Hono } from '../hono'6import { HTTPException } from '../http-exception'7import { cloneRawRequest } from '../request'8import type {9 ErrorHandler,10 ExtractSchema,11 ExtractSchemaForStatusCode,
1286 unmodified lines
1298 // Temporary: let's see what the actual type is1299 type TestActual = Actual1300 })1301})13021303describe('Raw Request cloning after validation', () => {1304 it('Should allow the `cloneRawRequest` util to clone the request object after validation', async () => {1305 const app = new Hono()13061307 app.post(1308 '/json-validation',1309 validator('json', (data) => data),1310 async (c) => {1311 const clonedReq = await cloneRawRequest(c.req)1312 const clonedJSON = await clonedReq.json()13131314 return c.json({1315 originalMethod: c.req.raw.method,1316 clonedMethod: clonedReq.method,1317 clonedUrl: clonedReq.url,1318 clonedHeaders: {1319 contentType: clonedReq.headers.get('Content-Type'),1320 customHeader: clonedReq.headers.get('X-Custom-Header'),1321 },1322 originalCache: c.req.raw.cache,1323 clonedCache: clonedReq.cache,1324 originalCredentials: c.req.raw.credentials,1325 clonedCredentials: clonedReq.credentials,1326 originalMode: c.req.raw.mode,1327 clonedMode: clonedReq.mode,1328 originalRedirect: c.req.raw.redirect,1329 clonedRedirect: clonedReq.redirect,1330 originalReferrerPolicy: c.req.raw.referrerPolicy,1331 clonedReferrerPolicy: clonedReq.referrerPolicy,1332 cloned: JSON.stringify(clonedJSON) === JSON.stringify(await c.req.json()),1333 payload: clonedJSON,1334 })1335 }1336 )13371338 const testData = { message: 'test', userId: 123 }1339 const res = await app.request('/json-validation', {1340 method: 'POST',1341 headers: {1342 'Content-Type': 'application/json',1343 'X-Custom-Header': 'test-value',1344 },1345 body: JSON.stringify(testData),1346 cache: 'no-cache',1347 credentials: 'include',1348 mode: 'cors',1349 redirect: 'follow',1350 referrerPolicy: 'origin',1351 })13521353 expect(res.status).toBe(200)13541355 const result = await res.json()13561357 expect(result.originalMethod).toBe('POST')1358 expect(result.clonedMethod).toBe('POST')1359 expect(result.clonedUrl).toBe('http://localhost/json-validation')1360 expect(result.clonedHeaders.contentType).toBe('application/json')1361 expect(result.clonedHeaders.customHeader).toBe('test-value')1362 expect(result.clonedCache).toBe(result.originalCache)1363 expect(result.clonedCredentials).toBe(result.originalCredentials)1364 expect(result.clonedMode).toBe(result.originalMode)1365 expect(result.clonedRedirect).toBe(result.originalRedirect)1366 expect(result.clonedReferrerPolicy).toBe(result.originalReferrerPolicy)1367 expect(result.cloned).toBe(true)1368 expect(result.payload).toMatchObject(testData)1369 })1370})
modified:src/request.test.ts+125 added-1 removed
1import { HonoRequest } from './request'1import { HTTPException } from './http-exception'2import { cloneRawRequest, HonoRequest } from './request'3import type { RouterRoute } from './types'45type RecursiveRecord<K extends string, T> = {6 [key in K]: T | RecursiveRecord<K, T>
371 unmodified lines
378 })379 })380 })381})382383describe('cloneRawRequest', () => {384 test('clones unconsumed request object', async () => {385 const req = new HonoRequest(386 new Request('http://localhost', {387 method: 'POST',388 headers: {389 'Content-Type': 'application/json',390 'X-Custom-Header': 'custom-value',391 },392 body: text,393 cache: 'no-cache',394 credentials: 'include',395 integrity: 'sha256-test',396 mode: 'cors',397 redirect: 'follow',398 referrer: 'http://example.com',399 referrerPolicy: 'origin',400 })401 )402403 const clonedReq = await cloneRawRequest(req)404405 expect(clonedReq.method).toBe('POST')406 expect(clonedReq.url).toBe('http://localhost/')407 expect(await clonedReq.text()).toBe(text)408 expect(clonedReq.headers.get('Content-Type')).toBe('application/json')409 expect(clonedReq.headers.get('X-Custom-Header')).toBe('custom-value')410 expect(clonedReq.cache).toBe('no-cache')411 expect(clonedReq.credentials).toBe('include')412 expect(clonedReq.integrity).toBe('sha256-test')413 expect(clonedReq.mode).toBe('cors')414 expect(clonedReq.redirect).toBe('follow')415 expect(clonedReq.referrer).toBe('http://example.com/')416 expect(clonedReq.referrerPolicy).toBe('origin')417 expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)418 expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)419 })420421 test('clones consumed request object', async () => {422 const req = new HonoRequest(423 new Request('http://localhost', {424 method: 'POST',425 headers: {426 Authorization: 'Bearer token123',427 },428 body: text,429 mode: 'same-origin',430 credentials: 'same-origin',431 })432 )433 await req.json()434435 const clonedReq = await cloneRawRequest(req)436437 expect(clonedReq.method).toBe('POST')438 expect(clonedReq.url).toBe('http://localhost/')439 expect(await clonedReq.json()).toEqual(json)440 expect(clonedReq.headers.get('Authorization')).toBe('Bearer token123')441 expect(clonedReq.mode).toBe('same-origin')442 expect(clonedReq.credentials).toBe('same-origin')443 expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)444 expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)445 })446447 test('clones GET request without body', async () => {448 const req = new HonoRequest(449 new Request('http://localhost', {450 method: 'GET',451 headers: {452 'User-Agent': 'test-agent',453 },454 cache: 'default',455 redirect: 'manual',456 referrerPolicy: 'no-referrer',457 })458 )459460 const clonedReq = await cloneRawRequest(req)461462 expect(clonedReq.method).toBe('GET')463 expect(clonedReq.url).toBe('http://localhost/')464 expect(clonedReq.headers.get('User-Agent')).toBe('test-agent')465 expect(clonedReq.cache).toBe('default')466 expect(clonedReq.redirect).toBe('manual')467 expect(clonedReq.referrerPolicy).toBe('no-referrer')468 expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)469 expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)470 })471472 test('clones request when raw body was consumed directly without HonoRequest methods', async () => {473 const req = new HonoRequest(474 new Request('http://localhost', {475 method: 'POST',476 headers: {477 'Content-Type': 'application/json',478 },479 body: text,480 })481 )482483 // Consume the raw request body directly, bypassing HonoRequest methods484 // This means bodyCache will be empty485 await req.raw.text()486487 expect(req.raw.bodyUsed).toBe(true)488 expect(Object.keys(req.bodyCache).length).toBe(0)489490 let error: HTTPException | undefined = undefined491 try {492 await cloneRawRequest(req)493 } catch (e) {494 expect(e).toBeInstanceOf(HTTPException)495 error = e as HTTPException496 }497498 expect(error).not.toBeUndefined()499 expect((error as HTTPException).status).toBe(500)500 expect((error as HTTPException).message).toContain(501 'Cannot clone request: body was already consumed and not cached'502 )503 })504})
modified:src/request.ts+68 added
1/* eslint-disable @typescript-eslint/no-explicit-any */2import { HTTPException } from './http-exception'3import { GET_MATCH_RESULT } from './request/constants'4import type { Result } from './router'5import type {6 Input,
18 unmodified lines
25 formData: FormData26}27type BodyCache = Partial<Body & { parsedBody: BodyData }>2829type OptionalRequestInitProperties = 'window' | 'priority'30type RequiredRequestInit = Required<Omit<RequestInit, OptionalRequestInitProperties>> & {31 [Key in OptionalRequestInitProperties]?: RequestInit[Key]32}3334const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)3536export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {37 /**
384 unmodified lines
422 get routePath(): string {423 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path424 }425}426427/**428 * Clones a HonoRequest's underlying raw Request object.429 *430 * This utility handles both consumed and unconsumed request bodies:431 * - If the request body hasn't been consumed, it uses the native `clone()` method432 * - If the request body has been consumed, it reconstructs a new Request using cached body data433 *434 * This is particularly useful when you need to:435 * - Process the same request body multiple times436 * - Pass requests to external services after validation437 *438 * @param req - The HonoRequest object to clone439 * @returns A Promise that resolves to a new Request object with the same properties440 * @throws {HTTPException} If the request body was consumed directly via `req.raw`441 * without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it442 * impossible to reconstruct the body from cache443 *444 * @example445 * ```ts446 * // Clone after consuming the body (e.g., after validation)447 * app.post('/forward',448 * validator('json', (data) => data),449 * async (c) => {450 * const validated = c.req.valid('json')451 * // Body has been consumed, but cloneRawRequest still works452 * const clonedReq = await cloneRawRequest(c.req)453 * return fetch('http://backend-service.com', clonedReq)454 * }455 * )456 * ```457 */458export const cloneRawRequest = async (req: HonoRequest): Promise<Request> => {459 if (!req.raw.bodyUsed) {460 return req.raw.clone()461 }462463 const cacheKey = (Object.keys(req.bodyCache) as Array<keyof Body>)[0]464 if (!cacheKey) {465 throw new HTTPException(500, {466 message:467 'Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.',468 })469 }470471 const requestInit: RequiredRequestInit = {472 body: await req[cacheKey](),473 cache: req.raw.cache,474 credentials: req.raw.credentials,475 headers: req.header(),476 integrity: req.raw.integrity,477 keepalive: req.raw.keepalive,478 method: req.method,479 mode: req.raw.mode,480 redirect: req.raw.redirect,481 referrer: req.raw.referrer,482 referrerPolicy: req.raw.referrerPolicy,483 signal: req.raw.signal,484 }485486 return new Request(req.url, requestInit)487}