/* eslint-disable @typescript-eslint/no-explicit-any */
import { HTTPException } from './http-exception'
import { GET_MATCH_RESULT } from './request/constants'
import type { Result } from './router'
import type {
Input,
InputToDataByTarget,
ParamKeyToRecord,
ParamKeys,
RemoveQuestion,
RouterRoute,
ValidationTargets,
} from './types'
import { parseBody } from './utils/body'
import type { BodyData, ParseBodyOptions } from './utils/body'
import type { CustomHeader, RequestHeader } from './utils/headers'
import type { Simplify, UnionToIntersection } from './utils/types'
import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'
type Body = {
json: any
text: string
arrayBuffer: ArrayBuffer
blob: Blob
formData: FormData
}
type BodyCache = Partial
type OptionalRequestInitProperties = 'window' | 'priority'
type RequiredRequestInit = Required> & {
[Key in OptionalRequestInitProperties]?: RequestInit[Key]
}
const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)
export class HonoRequest {
/**
* `.raw` can get the raw Request object.
*
* @see {@link https://hono.dev/docs/api/request#raw}
*
* @example
* ```ts
* // For Cloudflare Workers
* app.post('/', async (c) => {
* const metadata = c.req.raw.cf?.hostMetadata?
* ...
* })
* ```
*/
raw: Request
#validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData
#matchResult: Result<[unknown, RouterRoute]>
routeIndex: number = 0
/**
* `.path` can get the pathname of the request.
*
* @see {@link https://hono.dev/docs/api/request#path}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const pathname = c.req.path // `/about/me`
* })
* ```
*/
path: string
bodyCache: BodyCache = {}
constructor(
request: Request,
path: string = '/',
matchResult: Result<[unknown, RouterRoute]> = [[]]
) {
this.raw = request
this.path = path
this.#matchResult = matchResult
this.#validatedData = {}
}
/**
* `.req.param()` gets the path parameters.
*
* @see {@link https://hono.dev/docs/api/routing#path-parameter}
*
* @example
* ```ts
* const name = c.req.param('name')
* // or all parameters at once
* const { id, comment_id } = c.req.param()
* ```
*/
param = ParamKeys>(
key: string extends P ? never : P2 extends `${infer _}?` ? never : P2
): string
param> = RemoveQuestion>>(
key: P2
): string | undefined
param(key: string): string | undefined
param(): Simplify>>>
param(key?: string): unknown {
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()
}
#getDecodedParam(key: string): string | undefined {
const paramKey = this.#matchResult[0][this.routeIndex][1][key]
const param = this.#getParamValue(paramKey)
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param
}
#getAllDecodedParams(): Record {
const decoded: Record = {}
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])
for (const key of keys) {
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])
if (value !== undefined) {
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value
}
}
return decoded
}
#getParamValue(paramKey: any): string | undefined {
return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey
}
/**
* `.query()` can get querystring parameters.
*
* @see {@link https://hono.dev/docs/api/request#query}
*
* @example
* ```ts
* // Query params
* app.get('/search', (c) => {
* const query = c.req.query('q')
* })
*
* // Get all params at once
* app.get('/search', (c) => {
* const { q, limit, offset } = c.req.query()
* })
* ```
*/
query(key: string): string | undefined
query(): Record
query(key?: string) {
return getQueryParam(this.url, key)
}
/**
* `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B
*
* @see {@link https://hono.dev/docs/api/request#queries}
*
* @example
* ```ts
* app.get('/search', (c) => {
* // tags will be string[]
* const tags = c.req.queries('tags')
* })
* ```
*/
queries(key: string): string[] | undefined
queries(): Record
queries(key?: string) {
return getQueryParams(this.url, key)
}
/**
* `.header()` can get the request header value.
*
* @see {@link https://hono.dev/docs/api/request#header}
*
* @example
* ```ts
* app.get('/', (c) => {
* const userAgent = c.req.header('User-Agent')
* })
* ```
*/
header(name: RequestHeader): string | undefined
header(name: string): string | undefined
header(): Record
header(name?: string) {
if (name) {
return this.raw.headers.get(name) ?? undefined
}
const headerData: Record = {}
this.raw.headers.forEach((value, key) => {
headerData[key] = value
})
return headerData
}
/**
* `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`
*
* @see {@link https://hono.dev/docs/api/request#parsebody}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.parseBody()
* })
* ```
*/
async parseBody, T extends BodyData>(
options?: Options
): Promise
async parseBody(options?: Partial): Promise
async parseBody(options?: Partial) {
return parseBody(this, options)
}
#cachedBody = (key: keyof Body) => {
const { bodyCache, raw } = this
const cachedBody = bodyCache[key]
if (cachedBody) {
return cachedBody
}
const anyCachedKey = Object.keys(bodyCache)[0]
if (anyCachedKey) {
return (bodyCache[anyCachedKey as keyof Body] as Promise).then((body) => {
if (anyCachedKey === 'json') {
body = JSON.stringify(body)
}
return new Response(body)[key]()
})
}
return (bodyCache[key] = raw[key]())
}
/**
* `.json()` can parse Request body of type `application/json`
*
* @see {@link https://hono.dev/docs/api/request#json}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.json()
* })
* ```
*/
json(): Promise {
return this.#cachedBody('text').then((text: string) => JSON.parse(text))
}
/**
* `.text()` can parse Request body of type `text/plain`
*
* @see {@link https://hono.dev/docs/api/request#text}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.text()
* })
* ```
*/
text(): Promise {
return this.#cachedBody('text')
}
/**
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
*
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.arrayBuffer()
* })
* ```
*/
arrayBuffer(): Promise {
return this.#cachedBody('arrayBuffer')
}
/**
* Parses the request body as a `Blob`.
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.blob();
* });
* ```
* @see https://hono.dev/docs/api/request#blob
*/
blob(): Promise {
return this.#cachedBody('blob')
}
/**
* Parses the request body as `FormData`.
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.formData();
* });
* ```
* @see https://hono.dev/docs/api/request#formdata
*/
formData(): Promise {
return this.#cachedBody('formData')
}
/**
* Adds validated data to the request.
*
* @param target - The target of the validation.
* @param data - The validated data to add.
*/
addValidatedData(target: keyof ValidationTargets, data: {}) {
this.#validatedData[target] = data
}
/**
* Gets validated data from the request.
*
* @param target - The target of the validation.
* @returns The validated data.
*
* @see https://hono.dev/docs/api/request#valid
*/
valid(target: T): InputToDataByTarget
valid(target: keyof ValidationTargets) {
return this.#validatedData[target] as unknown
}
/**
* `.url()` can get the request url strings.
*
* @see {@link https://hono.dev/docs/api/request#url}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const url = c.req.url // `http://localhost:8787/about/me`
* ...
* })
* ```
*/
get url(): string {
return this.raw.url
}
/**
* `.method()` can get the method name of the request.
*
* @see {@link https://hono.dev/docs/api/request#method}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const method = c.req.method // `GET`
* })
* ```
*/
get method(): string {
return this.raw.method
}
get [GET_MATCH_RESULT](): Result<[unknown, RouterRoute]> {
return this.#matchResult
}
/**
* `.matchedRoutes()` can return a matched route in the handler
*
* @deprecated
*
* Use matchedRoutes helper defined in "hono/route" instead.
*
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
*
* @example
* ```ts
* app.use('*', async function logger(c, next) {
* await next()
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
* console.log(
* method,
* ' ',
* path,
* ' '.repeat(Math.max(10 - path.length, 0)),
* name,
* i === c.req.routeIndex ? '<- respond from here' : ''
* )
* })
* })
* ```
*/
get matchedRoutes(): RouterRoute[] {
return this.#matchResult[0].map(([[, route]]) => route)
}
/**
* `routePath()` can retrieve the path registered within the handler
*
* @deprecated
*
* Use routePath helper defined in "hono/route" instead.
*
* @see {@link https://hono.dev/docs/api/request#routepath}
*
* @example
* ```ts
* app.get('/posts/:id', (c) => {
* return c.json({ path: c.req.routePath })
* })
* ```
*/
get routePath(): string {
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path
}
}
/**
* Clones a HonoRequest's underlying raw Request object.
*
* This utility handles both consumed and unconsumed request bodies:
* - If the request body hasn't been consumed, it uses the native `clone()` method
* - If the request body has been consumed, it reconstructs a new Request using cached body data
*
* This is particularly useful when you need to:
* - Process the same request body multiple times
* - Pass requests to external services after validation
*
* @param req - The HonoRequest object to clone
* @returns A Promise that resolves to a new Request object with the same properties
* @throws {HTTPException} If the request body was consumed directly via `req.raw`
* without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it
* impossible to reconstruct the body from cache
*
* @example
* ```ts
* // Clone after consuming the body (e.g., after validation)
* app.post('/forward',
* validator('json', (data) => data),
* async (c) => {
* const validated = c.req.valid('json')
* // Body has been consumed, but cloneRawRequest still works
* const clonedReq = await cloneRawRequest(c.req)
* return fetch('http://backend-service.com', clonedReq)
* }
* )
* ```
*/
export const cloneRawRequest = async (req: HonoRequest): Promise => {
if (!req.raw.bodyUsed) {
return req.raw.clone()
}
const cacheKey = (Object.keys(req.bodyCache) as Array)[0]
if (!cacheKey) {
throw new HTTPException(500, {
message:
'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.',
})
}
const requestInit: RequiredRequestInit = {
body: await req[cacheKey](),
cache: req.raw.cache,
credentials: req.raw.credentials,
headers: req.header(),
integrity: req.raw.integrity,
keepalive: req.raw.keepalive,
method: req.method,
mode: req.raw.mode,
redirect: req.raw.redirect,
referrer: req.raw.referrer,
referrerPolicy: req.raw.referrerPolicy,
signal: req.raw.signal,
}
return new Request(req.url, requestInit)
}