H3

H3 class is the core of server.

You can create a new H3 app instance using new H3():

import { H3 } from "h3";

const app = new H3({
  /* optional config */
});

H3 Methods

H3.fetch

A fetch-compatible function allowing to fetch app routes.

const response = await app.fetch("/");
console.log(response, await response.text());

H3.on

Register route handler for specific HTTP method.

const app = new H3().on("GET", "/", () => "OK");
Read more in Routing.

H3.[method]

Register route handler for specific HTTP method (shortcut for app.on(method, ...)).

const app = new H3().get("/", () => "OK");

H3.all

Register route handler for all HTTP methods.

const app = new H3().all("/", () => "OK");

H3.use

Register a global middleware.

const app = new H3()
  .use((event) => {
    console.log(`request: ${event.req.url}`);
  })
  .all("/", () => "OK");
Read more in Middleware.

H3.register

Register a H3 plugin to extend app.

Read more in Plugins.

H3.handler

An H3 event handler useful to compose multiple H3 app instances.

Example: Nested apps.

import { H3, serve, redirect, withBase } from "h3";

const nestedApp = new H3().get("/test", () => "/test (sub app)");

const app = new H3()
  .get("/", (event) => redirect(event, "/api/test"))
  .all("/api/**", withBase("/api", nestedApp.handler));

serve(app);

H3.mount

Mount a .fetch compatible server instance like Hono or Elysia under the base URL.

import { H3 } from "h3";
import { Hono } from "hono";
import { Elysia } from "elysia";

const app = new H3()
  .mount(
    "/elysia",
    new Elysia().get("/test", () => "Hello Elysia!"),
  )
  .mount(
    "/hono",
    new Hono().get("/test", (c) => c.text("Hello Hono!")),
  );
Base prefix will be removed from request.url passed to the mounted app.
Similarly, you can mount an H3 app in Hono or Elysia.

H3 Options

You can pass global app configuration when initializing an app.

Supported options:

  • debug
  • plugins: (see plugins for more information)
Enabling debug option, sends important stuff like stack traces in error responses. Only enable during development.

Global Hooks

When initializing an H3 app, you can register global hooks:

  • onError
  • onRequest
  • onResponse

These hooks are called for every request and can be used to add global logic to your app such as logging, error handling, etc.

const app = new H3({
  onRequest: (event) => {
    console.log("Request:", event.req.url);
  },
  onResponse: (response, event) => {
    console.log("Response:", event.path, response.status);
  },
  onError: (error, event) => {
    console.error(error);
  },
});
Global hooks only run from main H3 app and not sub-apps. Use middleware for more flexibility.

H3 Properties

H3.config

Global H3 instance config.