UNPKG

h3

Version:

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

114 lines (79 loc) 2.77 kB
# H3Event > H3Event, carries incoming request, prepared response and context. With each HTTP request, H3 internally creates an `H3Event` object and passes it though event handlers until sending the response. <read-more></read-more> An event is passed through all the lifecycle hooks and composable utils to use it as context. **Example:** ```js 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` Methods ### `H3Event.waitUntil` Tell the runtime about an ongoing operation that shouldn't close until the promise resolves. ```js [app.mjs] import { logRequest } from "./tracing.mjs"; app.get("/", (event) => { request.waitUntil(logRequest(request)); return "OK"; }); ``` ```js [tracing.mjs] 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` Properties ### `H3Event.app?` Access to the H3 [application instance](/guide/api/h3). ### `H3Event.context` The 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 parameters - `matchedRoute`: Matched router route object. - `sessions`: Cached session data. - `basicAuth`: Basic authentication data. ### `H3Event.req` Incoming HTTP request info based on native [Web Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) with additional runtime addons (see [srvx docs](https://srvx.h3.dev/guide/handler#extended-request-context)). ```ts 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.url` Access to the full parsed request [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL). ### `H3Event.res` Prepared HTTP response status and headers. ```ts app.get("/", (event) => { event.res.status = 200; event.res.statusText = "OK"; event.res.headers.set("x-test", "works"); return "OK"; }); ``` <read-more></read-more>