| icon |
|---|
material-symbols:bolt-rounded |
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 */
});A fetch-compatible function allowing to fetch app routes.
const response = await app.request("/");
console.log(response, await response.text());Similar to H3.request but only accepts one (req: Request) argument for cross runtime compatibility.
Register route handler for specific HTTP method.
const app = new H3().on("GET", "/", () => "OK");:read-more{to="/guide/basics/routing" title="Routing"}
Register route handler for specific HTTP method (shortcut for app.on(method, ...)).
const app = new H3().get("/", () => "OK");Register route handler for all HTTP methods.
const app = new H3().all("/", () => "OK");Register a global middleware.
const app = new H3()
.use((event) => {
console.log(`request: ${event.req.url}`);
})
.all("/", () => "OK");:read-more{to="/guide/basics/middleware" title="Middleware"}
Register a H3 plugin to extend app.
:read-more{to="/guide/advanced/plugins" title="Plugins"}
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);Using .mount method, you can register a sub-app with prefix.
:read-more{to="/guide/basics/nested-apps" title="Nested Apps"}
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.plugins: (see plugins for more information)
Important
Enabling debug option, sends important stuff like stack traces in error responses. Only enable during development.
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.
Global H3 instance config.