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.request
A fetch-compatible function allowing to fetch app routes.
const response = await app.request("/");
console.log(response, await response.text());#H3.fetch
Similar to H3.request but only accepts one (req: Request) argument for cross runtime compatibility.
#H3.on
Register route handler for specific HTTP method.
const app = new H3().on("GET", "/", () => "OK");#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");#H3.register
Register a H3 plugin to extend app.
#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
Using .mount method, you can register a sub-app with prefix.
#H3 Options
You can pass global app configuration when initializing an app.
Supported options:
debug: Displays debugging stack traces in HTTP responses (potentially dangerous for production!).silent: When enabled, console errors for unhandled exceptions will not be displayed.allowMalformedURL: When enabled, requests with a malformed percent-encoded URL path (e.g./foo%,/%ZZ) are allowed through with the raw pathname instead of being rejected with a400 Bad Request(the default).plugins: (see plugins for more information)
Important
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:
onErroronRequestonResponse
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.url.pathname, response.status);
},
onError: (error, event) => {
console.error(error);
},
});Important
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.