More utils
More H3 utilities.
#Base
#withBase(base, input)
Returns a new event handler that removes the base url of the event before calling the original handler.
Example:
const api = new H3()
.get("/", () => "Hello API!");
const app = new H3();
.use("/api/**", withBase("/api", api.handler));#Event
#getEventContext(event)
Gets the context of the event, if it does not exists, initializes a new context on req.context.
#isEvent(input)
Checks if the input is an H3Event object.
#isHTTPEvent(input)
Checks if the input is an object with { req: Request } signature.
#mockEvent(_request, options?)
#Middleware
#bodyLimit(limit)
Define a middleware that limits the request body size to the specified limit.
The limit is enforced as the body is read (see {@link assertBodySize}), so an oversized body surfaces as a 413 Request Entity Too Large error when the handler consumes it (an honest oversized Content-Length is still rejected up-front). A body the handler never reads is not counted. If you need custom handling, use assertBodySize directly.
#onError(hook)
Define a middleware that runs when an error occurs.
You can return a new Response from the handler to gracefully handle the error.
#onRequest(hook)
Define a middleware that runs on each request.
#onResponse(hook)
Define a middleware that runs after Response is generated.
You can return a new Response from the handler to replace the original response.
#WebSocket
#defineWebSocket(hooks)
Define WebSocket hooks.
Example:
const hooks = defineWebSocket({
open: (peer) => peer.send("Welcome!"),
message: (peer, message) => peer.send(message.text()),
close: (peer) => console.log("closed", peer),
});#defineWebSocketHandler(http?)
Define WebSocket event handler.
By default, non-upgrade (plain HTTP) requests receive a 426 Upgrade Required response. Pass an http handler to serve those requests instead, allowing the same route to handle both WebSocket upgrades and regular HTTP requests. WebSocket upgrade requests always go to hooks.
Note: the http handler only handles non-upgrade requests. To reject or customize the upgrade handshake itself, use the crossws upgrade hook instead.
Example:
// WebSocket-only route (non-upgrade requests get `426 Upgrade Required`)
app.get(
"/_ws",
defineWebSocketHandler({
message: (peer, message) => peer.send(message.text()),
}),
);Example:
// Handle both WebSocket upgrades and plain HTTP on the same route
app.get(
"/_ws",
defineWebSocketHandler(
{ message: (peer, message) => peer.send(message.text()) },
() => "Send a WebSocket upgrade request to connect.",
),
);