docs/1.guide/4.event.md
Event object carries an incoming request and context.
Every time a new HTTP request comes, h3 internally creates an Event object and passes it though event handlers until sending the response.
An event is passed through all the lifecycle hooks and composable utils to use it as context.
Example:
import { defineEventHandler, getQuery, readBody } from "h3";
app.use(defineEventHandler(async (event) => {
// Log event. `.toString()` stringifies to a simple string like `[GET] /<path>`
console.log(`Request: ${event.toString()}`);
// Parse query params
const query = getQuery(event)
// Try to read request body
const body = await readBody(event).catch(() => {})
// Echo back request as response
return {
path: event.path,
method: event.method,
query,
body,
}
}));
The main properties of an event are:
event.nodeThe event.node allows you to access the native Node.js request and response. In runtimes other than Node.js/Bun, h3 makes a compatible shim using unjs/node-mock-http.
[!IMPORTANT] Try to avoid depending on
event.node.*context as much as you can and instead prefer h3 utils.
defineEventHandler((event) => {
event.node.req; // Node.js HTTP Request
event.node.res; // Node.js HTTP Response
});
event.web?If available, an object with request and url properties to access native web request context.
event.methodAccess to the normalized (uppercase) request method.
event.pathAccess to the request path. (Example: /test?test=123)
event.headersAccess to the normalized request Headers.
[!TIP] You can alternatively use
getHeaders(event)orgetHeader(event, name)for a simplified interface.
event.contextThe context is an object that contains arbitrary information about the request.
You can store your custom properties inside event.context to share across composable utils.
event.handledSpecifies if response is already handled or not. Initially for each request it is false, and when a response is generated, it is set to true.
Advanced: If you manually handle the response, set it to true to tell h3 stop sending any responses.
h3 provides a function to help you to create a response before the end of the request.
event.respondWithThe respondWith method is used to create a response without ending the request.
You must craft a response using the Response constructor.
[!TIP] Prefer explicit
returnoverrespondWithas best practice.
[!IMPORTANT] A
respondWithcall will always take precedence over the returned value, from current and next event handlers. If there is no returned value, the request will continue until the end of the stack runner.
Example:
defineEventHandler(async (event) => {
await event.respondWith(new Response("Hello World"));
return "..."; // DOES NOT WORKS
});
app.use(
defineEventHandler(async (event) => {
await event.respondWith(new Response("Hello World"));
return "..."; // DOES NOT WORK
}),
);
With this example, the client will receive Hello World.