h3@1.9.0 - jsDocs.io

Minimal H(TTP) framework built for high performance and portability.

Index
Variables
appendHeader
appendHeaders
eventHandler
getHeader
getHeaders
H3Headers
H3Response
lazyEventHandler
MIMES
setHeader
setHeaders
Functions
appendCorsHeaders()
appendCorsPreflightHeaders()
appendResponseHeader()
appendResponseHeaders()
assertMethod()
callNodeListener()
clearResponseHeaders()
clearSession()
createApp()
createAppEventHandler()
createError()
createEvent()
createRouter()
defaultContentType()
defineEventHandler()
defineLazyEventHandler()
defineNodeListener()
defineNodeMiddleware()
defineRequestMiddleware()
defineResponseMiddleware()
deleteCookie()
dynamicEventHandler()
fetchWithEvent()
fromNodeMiddleware()
fromPlainHandler()
fromWebHandler()
getCookie()
getMethod()
getProxyRequestHeaders()
getQuery()
getRequestFingerprint()
getRequestHeader()
getRequestHeaders()
getRequestHost()
getRequestIP()
getRequestPath()
getRequestProtocol()
getRequestURL()
getRequestWebStream()
getResponseHeader()
getResponseHeaders()
getResponseStatus()
getResponseStatusText()
getRouterParam()
getRouterParams()
getSession()
getValidatedQuery()
getValidatedRouterParams()
handleCacheHeaders()
handleCors()
isCorsOriginAllowed()
isError()
isEvent()
isEventHandler()
isMethod()
isPreflightRequest()
isStream()
isWebResponse()
parseCookies()
promisifyNodeListener()
proxyRequest()
readBody()
readFormData()
readMultipartFormData()
readRawBody()
readValidatedBody()
removeResponseHeader()
sanitizeStatusCode()
sanitizeStatusMessage()
sealSession()
send()
sendError()
sendNoContent()
sendProxy()
sendRedirect()
sendStream()
sendWebResponse()
serveStatic()
setCookie()
setResponseHeader()
setResponseHeaders()
setResponseStatus()
splitCookiesString()
toEventHandler()
toNodeListener()
toPlainHandler()
toWebHandler()
toWebRequest()
unsealSession()
updateSession()
use()
useBase()
useSession()
writeEarlyHints()
Classes
H3Error
H3Event
Interfaces
App
AppOptions
AppUse
CacheConditions
CreateRouterOptions
DynamicEventHandler
EventHandler
EventHandlerRequest
H3CorsOptions
H3EventContext
InputLayer
Layer
MultiPartData
NodeEventContext
PlainRequest
PlainResponse
ProxyOptions
RequestFingerprintOptions
RouteNode
Router
ServeStaticOptions
Session
SessionConfig
StaticAssetMeta
WebEventContext
Type Aliases
AddRouteShortcuts
Duplex
Encoding
EventHandlerObject
EventHandlerResponse
HTTPHeaderName
HTTPMethod
InferEventInput
InputStack
LazyEventHandler
Matcher
NodeListener
NodeMiddleware
NodePromisifiedHandler
PlainHandler
RequestHeaders
RouterMethod
RouterUse
SessionData
Stack
ValidateFunction
ValidateResult
WebHandler
Variables
variable appendHeader
const appendHeader: (
    event: H3Event<EventHandlerRequest>,
    name: HTTPHeaderName,
    value: string
) => void;
variable appendHeaders
const appendHeaders: (
    event: H3Event<EventHandlerRequest>,
    headers: Record<string, string>
) => void;
variable eventHandler
const eventHandler: {
    <Request extends EventHandlerRequest = EventHandlerRequest, Response = any>(
        handler:
            | EventHandler<Request, Response>
            | EventHandlerObject<Request, Response>
    ): EventHandler<Request, Response>;
    <Request = EventHandlerRequest, Response = any>(
        handler: EventHandler<
            Request extends EventHandlerRequest ? Request : EventHandlerRequest,
            Request extends EventHandlerRequest ? Response : Request
        >
    ): EventHandler<
        Request extends EventHandlerRequest ? Request : EventHandlerRequest,
        Request extends EventHandlerRequest ? Response : Request
    >;
};
variable getHeader
const getHeader: (
    event: H3Event<EventHandlerRequest>,
    name: HTTPHeaderName
) => string;
variable getHeaders
const getHeaders: (
    event: H3Event<EventHandlerRequest>
) => Partial<Record<HTTPHeaderName, string>>;
variable H3Headers
const H3Headers: {
    new (init?: HeadersInit | undefined): Headers;
    prototype: Headers;
};
Deprecated

Please use native web Headers https://developer.mozilla.org/en-US/docs/Web/API/Headers

variable H3Response
const H3Response: {
    new (
        body?: BodyInit | null | undefined,
        init?: ResponseInit | undefined
    ): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit | undefined): Response;
    redirect(url: string | URL, status?: number | undefined): Response;
};
Deprecated

Please use native web Response https://developer.mozilla.org/en-US/docs/Web/API/Response

variable lazyEventHandler
const lazyEventHandler: <T extends LazyEventHandler>(
    factory: T
) => Awaited<ReturnType<T>>;
variable MIMES
const MIMES: { html: string; json: string };
variable setHeader
const setHeader: (
    event: H3Event<EventHandlerRequest>,
    name: HTTPHeaderName,
    value: unknown
) => void;
variable setHeaders
const setHeaders: (
    event: H3Event<EventHandlerRequest>,
    headers: Record<string, unknown>
) => void;
Functions
function appendCorsHeaders
appendCorsHeaders: (event: H3Event, options: H3CorsOptions) => void;
function appendCorsPreflightHeaders
appendCorsPreflightHeaders: (event: H3Event, options: H3CorsOptions) => void;
function appendResponseHeader
appendResponseHeader: (
    event: H3Event,
    name: HTTPHeaderName,
    value: string
) => void;
function appendResponseHeaders
appendResponseHeaders: (event: H3Event, headers: Record<string, string>) => void;
function assertMethod
assertMethod: (
    event: H3Event,
    expected: HTTPMethod | HTTPMethod[],
    allowHead?: boolean
) => void;
function callNodeListener
callNodeListener: (
    handler: NodeMiddleware,
    req: IncomingMessage,
    res: ServerResponse
) => Promise<unknown>;
function clearResponseHeaders
clearResponseHeaders: (event: H3Event, headerNames?: string[]) => void;

Remove all response headers, or only those specified in the headerNames array.

Parameter event

H3 event

Parameter headerNames

Array of header names to remove

function clearSession
clearSession: (event: H3Event, config: Partial<SessionConfig>) => Promise<void>;
function createApp
createApp: (options?: AppOptions) => App;
function createAppEventHandler
createAppEventHandler: (
    stack: Stack,
    options: AppOptions
) => EventHandler<EventHandlerRequest, Promise<void>>;
function createError
createError: <DataT = any>(
    input:
        | string
        | (Partial<H3Error<DataT>> & { status?: number; statusText?: string })
) => H3Error;

Creates a new Error that can be used to handle both internal and runtime errors.

Parameter input

The error message or an object containing error properties. {H3Error} - An instance of H3Error.

function createEvent
createEvent: (req: IncomingMessage, res: ServerResponse) => H3Event;

Creates a new H3Event instance from the given Node.js request and response objects.

Parameter req

The NodeIncomingMessage object.

Parameter res

The NodeServerResponse object.

Returns

A new H3Event instance.

See Also

H3Event

function createRouter
createRouter: (opts?: CreateRouterOptions) => Router;
function defaultContentType
defaultContentType: (event: H3Event, type?: string) => void;
function defineEventHandler
defineEventHandler: {
    <Request extends EventHandlerRequest = EventHandlerRequest, Response = any>(
        handler:
            | EventHandler<Request, Response>
            | EventHandlerObject<Request, Response>
    ): EventHandler<Request, Response>;
    <Request = EventHandlerRequest, Response = any>(
        handler: EventHandler<
            Request extends EventHandlerRequest ? Request : EventHandlerRequest,
            Request extends EventHandlerRequest ? Response : Request
        >
    ): EventHandler<
        Request extends EventHandlerRequest ? Request : EventHandlerRequest,
        Request extends EventHandlerRequest ? Response : Request
    >;
};
function defineLazyEventHandler
defineLazyEventHandler: <T extends LazyEventHandler>(
    factory: T
) => Awaited<ReturnType<T>>;
function defineNodeListener
defineNodeListener: (handler: NodeListener) => NodeListener;
function defineNodeMiddleware
defineNodeMiddleware: (middleware: NodeMiddleware) => NodeMiddleware;
function defineRequestMiddleware
defineRequestMiddleware: <
    Request extends EventHandlerRequest = EventHandlerRequest
>(
    fn: _RequestMiddleware<Request>
) => _RequestMiddleware<Request>;
function defineResponseMiddleware
defineResponseMiddleware: <
    Request extends EventHandlerRequest = EventHandlerRequest
>(
    fn: _ResponseMiddleware<Request>
) => _ResponseMiddleware<Request>;
function deleteCookie
deleteCookie: (
    event: H3Event,
    name: string,
    serializeOptions?: CookieSerializeOptions
) => void;

Remove a cookie by name.

Parameter event

H3 event or res passed by h3 handler

Parameter name

Name of the cookie to delete

Parameter serializeOptions

Cookie options

deleteCookie(res, 'SessionId')
function dynamicEventHandler
dynamicEventHandler: (initial?: EventHandler) => DynamicEventHandler;
function fetchWithEvent
fetchWithEvent: <
    T = unknown,
    _R = any,
    F extends (req: RequestInfo | URL, opts?: any) => any = (
        input: URL | RequestInfo,
        init?: RequestInit
    ) => Promise<Response>
>(
    event: H3Event,
    req: RequestInfo | URL,
    init?: RequestInit & { context?: H3EventContext },
    options?: { fetch: F }
) => unknown extends T ? ReturnType<F> : T;
function fromNodeMiddleware
fromNodeMiddleware: (handler: NodeListener | NodeMiddleware) => EventHandler;
function fromPlainHandler
fromPlainHandler: (
    handler: PlainHandler
) => EventHandler<EventHandlerRequest, Promise<unknown>>;

Modifiers
@experimental
function fromWebHandler
fromWebHandler: (
    handler: WebHandler
) => EventHandler<EventHandlerRequest, Promise<Response>>;

Modifiers
@experimental
function getCookie
getCookie: (event: H3Event, name: string) => string | undefined;

Get a cookie value by name.

Parameter event

H3 event or req passed by h3 handler

Parameter name

Name of the cookie to get

Returns

{*} Value of the cookie (String or undefined)

const authorization = getCookie(request, 'Authorization')
function getMethod
getMethod: (event: H3Event, defaultMethod?: HTTPMethod) => HTTPMethod;
Deprecated

Directly use event.method instead.

function getProxyRequestHeaders
getProxyRequestHeaders: (event: H3Event) => any;
function getQuery
getQuery: <
    T,
    Event extends H3Event<EventHandlerRequest> = H3Event<EventHandlerRequest>,
    _T = Exclude<InferEventInput<'query', Event, T>, undefined>
>(
    event: Event
) => _T;
function getRequestFingerprint
getRequestFingerprint: (
    event: H3Event,
    opts?: RequestFingerprintOptions
) => Promise<string | null>;

Behavior of this utility might change in the future versions

Modifiers
@experimental
function getRequestHeader
getRequestHeader: (
    event: H3Event,
    name: HTTPHeaderName
) => RequestHeaders[string];
function getRequestHeaders
getRequestHeaders: (event: H3Event) => RequestHeaders;
function getRequestHost
getRequestHost: (event: H3Event, opts?: { xForwardedHost?: boolean }) => string;
function getRequestIP
getRequestIP: (
    event: H3Event,
    opts?: { xForwardedFor?: boolean }
) => string | undefined;
function getRequestPath
getRequestPath: (event: H3Event) => string;
Deprecated

Use event.path instead

function getRequestProtocol
getRequestProtocol: (
    event: H3Event,
    opts?: { xForwardedProto?: boolean }
) => 'https' | 'http';
function getRequestURL
getRequestURL: (
    event: H3Event,
    opts?: { xForwardedHost?: boolean; xForwardedProto?: boolean }
) => URL;
function getRequestWebStream
getRequestWebStream: (event: H3Event) => undefined | ReadableStream;

Captures a stream from a request.

Parameter event

The H3Event object containing the request information.

Returns

Undefined if the request can't transport a payload, otherwise a ReadableStream of the request body.

function getResponseHeader
getResponseHeader: (
    event: H3Event,
    name: HTTPHeaderName
) => ReturnType<H3Event['res']['getHeader']>;
function getResponseHeaders
getResponseHeaders: (event: H3Event) => ReturnType<H3Event['res']['getHeaders']>;
function getResponseStatus
getResponseStatus: (event: H3Event) => number;
function getResponseStatusText
getResponseStatusText: (event: H3Event) => string;
function getRouterParam
getRouterParam: (
    event: H3Event,
    name: string,
    opts?: { decode?: boolean }
) => string | undefined;
function getRouterParams
getRouterParams: (
    event: H3Event,
    opts?: { decode?: boolean }
) => NonNullable<H3Event['context']['params']>;
function getSession
getSession: <T extends SessionDataT = SessionDataT>(
    event: H3Event,
    config: SessionConfig
) => Promise<Session<T>>;
function getValidatedQuery
getValidatedQuery: <
    T,
    Event extends H3Event<EventHandlerRequest> = H3Event<EventHandlerRequest>,
    _T = InferEventInput<'query', Event, T>
>(
    event: Event,
    validate: ValidateFunction<_T>
) => Promise<_T>;
function getValidatedRouterParams
getValidatedRouterParams: <
    T,
    Event extends H3Event<EventHandlerRequest> = H3Event<EventHandlerRequest>,
    _T = InferEventInput<'routerParams', Event, T>
>(
    event: Event,
    validate: ValidateFunction<_T>,
    opts?: { decode?: boolean }
) => Promise<_T>;
function handleCacheHeaders
handleCacheHeaders: (event: H3Event, opts: CacheConditions) => boolean;

Check request caching headers (If-Modified-Since) and add caching headers (Last-Modified, Cache-Control) Note: public cache control will be added by default

Returns

true when cache headers are matching. When true is returned, no reponse should be sent anymore

function handleCors
handleCors: (event: H3Event, options: H3CorsOptions) => boolean;
function isCorsOriginAllowed
isCorsOriginAllowed: (
    origin: ReturnType<typeof getRequestHeaders>['origin'],
    options: H3CorsOptions
) => boolean;
function isError
isError: (input: any) => input is H3Error<any>;

Checks if the given input is an instance of H3Error.

Parameter input

The input to check. {boolean} - Returns true if the input is an instance of H3Error, false otherwise.

function isEvent
isEvent: (input: any) => input is H3Event<EventHandlerRequest>;

Checks if the input is an H3Event object.

Parameter input

The input to check.

Returns

True if the input is an H3Event object, false otherwise.

See Also

H3Event

function isEventHandler
isEventHandler: (input: any) => input is EventHandler<EventHandlerRequest, any>;

Checks if any kind of input is an event handler.

Parameter input

The input to check.

Returns

True if the input is an event handler, false otherwise.

function isMethod
isMethod: (
    event: H3Event,
    expected: HTTPMethod | HTTPMethod[],
    allowHead?: boolean
) => boolean;
function isPreflightRequest
isPreflightRequest: (event: H3Event) => boolean;
function isStream
isStream: (data: any) => data is any;
function isWebResponse
isWebResponse: (data: any) => data is Response;
function parseCookies
parseCookies: (event: H3Event) => Record<string, string>;

Parse the request to get HTTP Cookie header string and returning an object of all cookie name-value pairs.

Parameter event

H3 event or req passed by h3 handler

Returns

Object of cookie name-value pairs

const cookies = parseCookies(event)
function promisifyNodeListener
promisifyNodeListener: (
    handler: NodeListener | NodeMiddleware
) => NodePromisifiedHandler;
function proxyRequest
proxyRequest: (
    event: H3Event,
    target: string,
    opts?: ProxyOptions
) => Promise<any>;
function readBody
readBody: <
    T,
    Event extends H3Event<EventHandlerRequest> = H3Event<EventHandlerRequest>,
    _T = InferEventInput<'body', Event, T>
>(
    event: Event,
    options?: { strict?: boolean }
) => Promise<_T>;

Reads request body and tries to safely parse using [destr](https://github.com/unjs/destr).

Parameter event

H3 event passed by h3 handler

Parameter encoding

The character encoding to use, defaults to 'utf-8'.

{*} The Object, Array, String, Number, Boolean, or null value corresponding to the request JSON body

const body = await readBody(event)
function readFormData
readFormData: (event: H3Event) => Promise<FormData>;

Constructs a FormData object from an event, after converting it to a a web request.

Parameter event

The H3Event object to read the form data from.

const eventHandler = event => {
  const formData = await readFormData(event)
  const email = formData.get("email")
  const password = formData.get("password")
 }
function readMultipartFormData
readMultipartFormData: (event: H3Event) => Promise<MultiPartData[] | undefined>;

Tries to read and parse the body of a an H3Event as multipart form.

Parameter event

The H3Event object to read multipart form from.

The parsed form data. If no form could be detected because the content type is not multipart/form-data or no boundary could be found.

const formData = await readMultipartFormData(event)
// The result could look like:
// [
//   {
//     "data": "other",
//     "name": "baz",
//   },
//   {
//     "data": "something",
//     "name": "some-other-data",
//   },
// ]
function readRawBody
readRawBody: <E extends Encoding = 'utf8'>(
    event: H3Event,
    encoding?: E
) => E extends false ? Promise<Buffer | undefined> : Promise<string | undefined>;

Reads body of the request and returns encoded raw string (default), or Buffer if encoding is falsy.

Parameter event

H3 event or req passed by h3 handler

Parameter encoding

encoding="utf-8" - The character encoding to use.

{String|Buffer} Encoded raw string or raw Buffer of the body

function readValidatedBody
readValidatedBody: <
    T,
    Event extends H3Event<EventHandlerRequest> = H3Event<EventHandlerRequest>,
    _T = InferEventInput<'body', Event, T>
>(
    event: Event,
    validate: ValidateFunction<_T>
) => Promise<_T>;

Tries to read the request body via readBody, then uses the provided validation function and either throws a validation error or returns the result.

Parameter event

The H3Event passed by the handler.

Parameter validate

The function to use for body validation. It will be called passing the read request body. If the result is not false, the parsed body will be returned.

Throws

If the validation function returns false or throws, a validation error will be thrown. {*} The Object, Array, String, Number, Boolean, or null value corresponding to the request JSON body.

See Also

{readBody}

// With a custom validation function
const body = await readValidatedBody(event, (body) => {
  return typeof body === "object" && body !== null
})


// With a zod schema
import { z } from 'zod'
const objectSchema = z.object()
const body = await readValidatedBody(event, objectSchema.safeParse)
function removeResponseHeader
removeResponseHeader: (event: H3Event, name: HTTPHeaderName) => void;
function sanitizeStatusCode
sanitizeStatusCode: (
    statusCode?: string | number,
    defaultStatusCode?: number
) => number;
function sanitizeStatusMessage
sanitizeStatusMessage: (statusMessage?: string) => string;
function sealSession
sealSession: <T extends SessionDataT = SessionDataT>(
    event: H3Event,
    config: SessionConfig
) => Promise<string>;
function send
send: (event: H3Event, data?: any, type?: string) => Promise<void>;
function sendError
sendError: (event: H3Event, error: Error | H3Error, debug?: boolean) => void;

Receives an error and returns the corresponding response. H3 internally uses this function to handle unhandled errors. Note that calling this function will close the connection and no other data will be sent to the client afterwards.

Parameter event

H3 event or req passed by h3 handler.

Parameter error

The raised error.

Parameter debug

Whether the application is in debug mode. In the debug mode, the stack trace of errors will be returned in the response.

function sendNoContent
sendNoContent: (event: H3Event, code?: number) => void;

Respond with an empty payload. Note that calling this function will close the connection and no other data can be sent to the client afterwards.

Parameter event

H3 event

Parameter code

status code to be send. By default, it is 204 No Content.

function sendProxy
sendProxy: (event: H3Event, target: string, opts?: ProxyOptions) => Promise<any>;
function sendRedirect
sendRedirect: (event: H3Event, location: string, code?: number) => Promise<void>;
function sendStream
sendStream: (event: H3Event, stream: Readable | ReadableStream) => Promise<void>;
function sendWebResponse
sendWebResponse: (event: H3Event, response: Response) => void | Promise<void>;
function serveStatic
serveStatic: (
    event: H3Event,
    options: ServeStaticOptions
) => Promise<void | false>;
function setCookie
setCookie: (
    event: H3Event,
    name: string,
    value: string,
    serializeOptions?: CookieSerializeOptions
) => void;

Set a cookie value by name.

Parameter event

H3 event or res passed by h3 handler

Parameter name

Name of the cookie to set

Parameter value

Value of the cookie to set

Parameter serializeOptions

Options for serializing the cookie

setCookie(res, 'Authorization', '1234567')
function setResponseHeader
setResponseHeader: (
    event: H3Event,
    name: HTTPHeaderName,
    value: Parameters<OutgoingMessage['setHeader']>[1]
) => void;
function setResponseHeaders
setResponseHeaders: (
    event: H3Event,
    headers: Record<string, Parameters<OutgoingMessage['setHeader']>[1]>
) => void;
function setResponseStatus
setResponseStatus: (event: H3Event, code?: number, text?: string) => void;
function splitCookiesString
splitCookiesString: (cookiesString: string | string[]) => string[];

Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas that are within a single set-cookie field-value, such as in the Expires portion. This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2 Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128 Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25 Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation https://github.com/nfriedly/set-cookie-parser/blob/3eab8b7d5d12c8ed87832532861c1a35520cf5b3/lib/set-cookie.js#L144

function toEventHandler
toEventHandler: (input: any, _?: any, _route?: string) => EventHandler;
function toNodeListener
toNodeListener: (app: App) => NodeListener;
function toPlainHandler
toPlainHandler: (app: App) => PlainHandler;

Modifiers
@experimental
function toWebHandler
toWebHandler: (app: App) => WebHandler;

Modifiers
@experimental
function toWebRequest
toWebRequest: (event: H3Event) => Request;
function unsealSession
unsealSession: (
    _event: H3Event,
    config: SessionConfig,
    sealed: string
) => Promise<Partial<Session<SessionDataT>>>;
function updateSession
updateSession: <T extends SessionDataT = SessionDataT>(
    event: H3Event,
    config: SessionConfig,
    update?: SessionUpdate<T>
) => Promise<Session<T>>;
function use
use: (
    app: App,
    arg1: string | EventHandler | InputLayer | InputLayer[],
    arg2?: Partial<InputLayer> | EventHandler | EventHandler[],
    arg3?: Partial<InputLayer>
) => App;
function useBase
useBase: (base: string, handler: EventHandler) => EventHandler;

Prefixes and executes a handler with a base path.

Parameter base

The base path to prefix. When set to an empty string, the handler will be run as is.

Parameter handler

The event handler to use with the adapted path.

function useSession
useSession: <T extends SessionDataT = SessionDataT>(
    event: H3Event,
    config: SessionConfig
) => Promise<{
    readonly id: string | undefined;
    readonly data: T;
    update: (update: SessionUpdate<T>) => Promise<any>;
    clear: () => Promise<any>;
}>;
function writeEarlyHints
writeEarlyHints: (
    event: H3Event,
    hints: string | string[] | Record<string, string | string[]>,
    cb?: () => void
) => void;
Classes
class H3Error
class H3Error<DataT = any> extends Error {}

H3 Runtime Error Error {number} statusCode - An integer indicating the HTTP response status code. {string} statusMessage - A string representing the HTTP status message. {boolean} fatal - Indicates if the error is a fatal error. {boolean} unhandled - Indicates if the error was unhandled and auto captured. {DataT} data - An extra data that will be included in the response. This can be used to pass additional information about the error. {boolean} internal - Setting this property to true will mark the error as an internal error.

constructor
constructor(message: string, opts?: { cause?: unknown });
property cause
cause?: {};
property data
data?: {};
property fatal
fatal: boolean;
property statusCode
statusCode: number;
property statusMessage
statusMessage?: string;
property unhandled
unhandled: boolean;
method toJSON
toJSON: () => Pick<
    H3Error<DataT>,
    'data' | 'statusCode' | 'statusMessage' | 'message'
>;
class H3Event
class H3Event<_RequestT extends EventHandlerRequest = EventHandlerRequest>
    implements Pick<FetchEvent, 'respondWith'> {}
constructor
constructor(req: IncomingMessage, res: ServerResponse);
property "__is_event__"
'__is_event__': boolean;
property context
context: H3EventContext;
property handled
readonly handled: boolean;
property headers
readonly headers: Headers;
property method
readonly method: HTTPMethod;
property node
node: NodeEventContext;
property path
readonly path: string;
property req
readonly req: any;
Deprecated

Please use event.node.req instead. *

property res
readonly res: ServerResponse<IncomingMessage>;
Deprecated

Please use event.node.res instead. *

property web
web?: WebEventContext;
method respondWith
respondWith: (response: Response | PromiseLike<Response>) => Promise<void>;
method toJSON
toJSON: () => string;
method toString
toString: () => string;
Interfaces
interface App
interface App {}
property handler
handler: EventHandler;
property options
options: AppOptions;
property stack
stack: Stack;
property use
use: AppUse;
interface AppOptions
interface AppOptions {}
property debug
debug?: boolean;
property onAfterResponse
onAfterResponse?: (
    event: H3Event,
    response?: {
        body?: unknown;
    }
) => void | Promise<void>;
property onBeforeResponse
onBeforeResponse?: (
    event: H3Event,
    response: {
        body?: unknown;
    }
) => void | Promise<void>;
property onError
onError?: (error: H3Error, event: H3Event) => any;
property onRequest
onRequest?: (event: H3Event) => void | Promise<void>;
interface AppUse
interface AppUse {}
call signature
(
    route: string | string[],
    handler: EventHandler | EventHandler[],
    options?: Partial<InputLayer>
): App;
call signature
(handler: EventHandler | EventHandler[], options?: Partial<InputLayer>): App;
call signature
(options: InputLayer): App;
interface CacheConditions
interface CacheConditions {}
property cacheControls
cacheControls?: string[];
property etag
etag?: string;
property maxAge
maxAge?: number;
property modifiedTime
modifiedTime?: string | Date;
interface CreateRouterOptions
interface CreateRouterOptions {}
property preemptive
preemptive?: boolean;
property preemtive
preemtive?: boolean;
Deprecated

Please use preemptive instead. *

interface DynamicEventHandler
interface DynamicEventHandler extends EventHandler {}
property set
set: (handler: EventHandler) => void;
interface EventHandler
interface EventHandler<
    Request extends EventHandlerRequest = EventHandlerRequest,
    Response extends EventHandlerResponse = EventHandlerResponse
> {}
call signature
(event: H3Event<Request>): Response;
interface EventHandlerRequest
interface EventHandlerRequest {}
property body
body?: any;
property query
query?: QueryObject;
property routerParams
routerParams?: Record<string, string>;
interface H3CorsOptions
interface H3CorsOptions {}
property allowHeaders
allowHeaders?: '*' | string[];
property credentials
credentials?: boolean;
property exposeHeaders
exposeHeaders?: '*' | string[];
property maxAge
maxAge?: string | false;
property methods
methods?: '*' | HTTPMethod[];
property origin
origin?: '*' | 'null' | (string | RegExp)[] | ((origin: string) => boolean);
property preflight
preflight?: {
    statusCode?: number;
};
interface H3EventContext
interface H3EventContext extends Record<string, any> {}
property clientAddress
clientAddress?: string;
property matchedRoute
matchedRoute?: RouteNode;

Matched router Node

The object structure may change in non-major version.

Modifiers
@experimental
property params
params?: Record<string, string>;
property sessions
sessions?: Record<string, Session>;
interface InputLayer
interface InputLayer {}
property handler
handler: EventHandler;
property lazy
lazy?: boolean;
property match
match?: Matcher;
property route
route?: string;
interface Layer
interface Layer {}
property handler
handler: EventHandler;
property match
match?: Matcher;
property route
route: string;
interface MultiPartData
interface MultiPartData {}
property data
data: Buffer;
property filename
filename?: string;
property name
name?: string;
property type
type?: string;
interface NodeEventContext
interface NodeEventContext {}
property req
req: IncomingMessage & {
    originalUrl?: string;
};
property res
res: ServerResponse;
interface PlainRequest
interface PlainRequest {}
property body
body?: null | BodyInit;
property context
context?: Record<string, unknown>;
property headers
headers: HeadersInit;
property method
method: string;
property path
path: string;
interface PlainResponse
interface PlainResponse {}
property body
body?: unknown;
property headers
headers: [string, string][];
property status
status: number;
property statusText
statusText: string;
interface ProxyOptions
interface ProxyOptions {}
property cookieDomainRewrite
cookieDomainRewrite?: string | Record<string, string>;
property cookiePathRewrite
cookiePathRewrite?: string | Record<string, string>;
property fetch
fetch?: typeof fetch;
property fetchOptions
fetchOptions?: RequestInit & {
    duplex?: Duplex;
} & {
    ignoreResponseError?: boolean;
};
property headers
headers?: RequestHeaders | HeadersInit;
property onResponse
onResponse?: (event: H3Event, response: Response) => void;
property sendStream
sendStream?: boolean;
property streamRequest
streamRequest?: boolean;
interface RequestFingerprintOptions
interface RequestFingerprintOptions {}
property hash
hash?: false | 'SHA-1';

SHA-1

property ip
ip?: boolean;

true

property method
method?: boolean;

false

property path
path?: boolean;

false

property userAgent
userAgent?: boolean;

false

property xForwardedFor
xForwardedFor?: boolean;

false

interface RouteNode
interface RouteNode {}
property handlers
handlers: Partial<Record<RouterMethod | 'all', EventHandler>>;
property path
path: string;
interface Router
interface Router extends AddRouteShortcuts {}
property add
add: RouterUse;
property handler
handler: EventHandler;
property use
use: RouterUse;
interface ServeStaticOptions
interface ServeStaticOptions {}
property encodings
encodings?: Record<string, string>;

Map of supported encodings (compressions) and their file extensions.

Each extension will be appended to the asset path to find the compressed version of the asset.

Example 1

{ gzip: ".gz", br: ".br" }

property fallthrough
fallthrough?: boolean;

When set to true, the function will not throw 404 error when the asset meta is not found or meta validation failed

property getContents
getContents: (id: string) => unknown | Promise<unknown>;

This function should resolve asset content

property getMeta
getMeta: (
    id: string
) => StaticAssetMeta | undefined | Promise<StaticAssetMeta | undefined>;

This function should resolve asset meta

property indexNames
indexNames?: string[];

Default index file to serve when the path is a directory

["/index.html"]

interface Session
interface Session<T extends SessionDataT = SessionDataT> {}
property createdAt
createdAt: number;
property data
data: SessionData<T>;
property id
id: string;
interface SessionConfig
interface SessionConfig {}
property cookie
cookie?: false | CookieSerializeOptions;

Default is secure, httpOnly, /

property crypto
crypto?: Crypto;
property generateId
generateId?: () => string;

Default is Crypto.randomUUID

property maxAge
maxAge?: number;

Session expiration time in seconds

property name
name?: string;

default is h3

property password
password: string;

Private key used to encrypt session tokens

property seal
seal?: SealOptions;
property sessionHeader
sessionHeader?: false | string;

Default is x-h3-session / x-{name}-session

interface StaticAssetMeta
interface StaticAssetMeta {}
property encoding
encoding?: string;
property etag
etag?: string;
property mtime
mtime?: number | string | Date;
property path
path?: string;
property size
size?: number;
property type
type?: string;
interface WebEventContext
interface WebEventContext {}
property request
request?: Request;
property url
url?: URL;
Type Aliases
type AddRouteShortcuts
type AddRouteShortcuts = Record<RouterMethod, RouterUse>;
type Duplex
type Duplex = 'half' | 'full';
type Encoding
type Encoding =
    | false
    | 'ascii'
    | 'utf8'
    | 'utf-8'
    | 'utf16le'
    | 'ucs2'
    | 'ucs-2'
    | 'base64'
    | 'latin1'
    | 'binary'
    | 'hex';
type EventHandlerObject
type EventHandlerObject<
    Request extends EventHandlerRequest = EventHandlerRequest,
    Response extends EventHandlerResponse = EventHandlerResponse
> = {
    onRequest?: _RequestMiddleware<Request> | _RequestMiddleware<Request>[];
    onBeforeResponse?:
        | _ResponseMiddleware<Request, Response>
        | _ResponseMiddleware<Request, Response>[];
    handler: EventHandler<Request, Response>;
};
type EventHandlerResponse
type EventHandlerResponse<T = any> = T | Promise<T>;
type HTTPHeaderName
type HTTPHeaderName = _HTTPHeaderName | Lowercase<_HTTPHeaderName> | (string & {});
type HTTPMethod
type HTTPMethod =
    | 'GET'
    | 'HEAD'
    | 'PATCH'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'CONNECT'
    | 'OPTIONS'
    | 'TRACE';
type InferEventInput
type InferEventInput<
    Key extends keyof EventHandlerRequest,
    Event extends H3Event,
    T
> = void extends T ? (Event extends H3Event<infer E> ? E[Key] : never) : T;
type InputStack
type InputStack = InputLayer[];
type LazyEventHandler
type LazyEventHandler = () => EventHandler | Promise<EventHandler>;
type Matcher
type Matcher = (url: string, event?: H3Event) => boolean;
type NodeListener
type NodeListener = (req: IncomingMessage, res: ServerResponse) => void;
type NodeMiddleware
type NodeMiddleware = (
    req: IncomingMessage,
    res: ServerResponse,
    next: (err?: Error) => any
) => any;
type NodePromisifiedHandler
type NodePromisifiedHandler = (
    req: IncomingMessage,
    res: ServerResponse
) => Promise<any>;
type PlainHandler
type PlainHandler = (request: PlainRequest) => Promise<PlainResponse>;
type RequestHeaders
type RequestHeaders = Partial<Record<HTTPHeaderName, string | undefined>>;
type RouterMethod
type RouterMethod = Lowercase<HTTPMethod>;
type RouterUse
type RouterUse = (
    path: string,
    handler: EventHandler,
    method?: RouterMethod | RouterMethod[]
) => Router;
type SessionData
type SessionData<T extends SessionDataT = SessionDataT> = T;
type Stack
type Stack = Layer[];
type ValidateFunction
type ValidateFunction<T> = (
    data: unknown
) => ValidateResult<T> | Promise<ValidateResult<T>>;
type ValidateResult
type ValidateResult<T> = T | true | false | void;
type WebHandler
type WebHandler = (
    request: Request,
    context?: Record<string, unknown>
) => Promise<Response>;

Modifiers
@experimental
Package Files (1)
dist/index.d.ts
Dependencies (8)
cookie-es
defu
destr
iron-webcrypto
radix3
ufo
uncrypto
unenv
Dev Dependencies (23)
@types/express
@types/node
@types/supertest
@vitest/coverage-v8
0x
autocannon
changelogen
connect
eslint
eslint-config-unjs
express
get-port
jiti
listhen
node-fetch-native
prettier
react
react-dom
supertest
typescript
unbuild
vitest
zod
Peer Dependencies (0)

No peer dependencies.

Badge

To add a badge like this oneto your package's README, use the codes available below.

You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/h3.

Markdown
[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/h3)
HTML
<a href="https://www.jsdocs.io/package/h3"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
Updated 8 days ago.
Package analyzed in 6071 ms.
Missing or incorrect documentation? Open an issue for this package.
Back to top