With each HTTP request, H3 internally creates an H3Event 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:
app.get("/", async (event) => {
// Log HTTP request
console.log(`[${event.req.method}] ${event.req.url}`);
// Parsed URL and query params
const searchParams = event.url.searchParams;
// Try to read request JSON body
const jsonBody = await event.req.json().catch(() => {});
return "OK";
});
H3Event MethodsH3Event.waitUntilTell the runtime about an ongoing operation that shouldn't close until the promise resolves.
import { logRequest } from "./tracing.mjs";
app.get("/", (event) => {
request.waitUntil(logRequest(request));
return "OK";
});
export async function logRequest(request) {
await fetch("https://telemetry.example.com", {
method: "POST",
body: JSON.stringify({
method: request.method,
url: request.url,
ip: request.ip,
}),
});
}
H3Event PropertiesH3Event.app?Access to the H3 application instance.
H3Event.contextThe context is an object that contains arbitrary information about the request.
You can store your custom properties inside event.context to share across utils.
Known context keys:
context.params: Matched router parameters.middlewareParams: Matched middleware parametersmatchedRoute: Matched router route object.sessions: Cached session data.basicAuth: Basic authentication data.H3Event.reqIncoming HTTP request info based on native Web Request with additional runtime addons (see srvx docs).
app.get("/", async (event) => {
const url = event.req.url;
const method = event.req.method;
const headers = event.req.headers;
// (note: you can consume body only once with either of this)
const bodyStream = await event.req.body;
const textBody = await event.req.text();
const jsonBody = await event.req.json();
const formDataBody = await event.req.formData();
return "OK";
});
H3Event.urlAccess to the full parsed request URL.
H3Event.resPrepared HTTP response status and headers.
app.get("/", (event) => {
event.res.status = 200;
event.res.statusText = "OK";
event.res.headers.set("x-test", "works");
return "OK";
});