Guide

Event Object

Event object carries incoming request, prepared response 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:

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

H3 Event Properties

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

event.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();

  return "OK";
});

event.url

Access to the full parsed request URL.

event.res

Prepared HTTP response based on partial Response options.

Example:

app.get("/", (event) => {
  event.res.status = 200;
  event.res.statusText = "OK";
  event.res.headers.set("x-test", "works");

  return "OK";
});