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 in Request Lifecycle.

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 Methods

H3Event.waitUntil

Tell 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";
});

H3Event Properties

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 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.url

Access to the full parsed request URL.

H3Event.res

Prepared 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";
});
Read more in Preparing Response.