You can create a new H3 app instance using new H3():
import { H3 } from "h3";
const app = new H3({
/* optional config */
});
H3 MethodsH3.requestA fetch-compatible function allowing to fetch app routes.
const response = await app.request("/");
console.log(response, await response.text());
H3.fetchSimilar to H3.request but only accepts one (req: Request) argument for cross runtime compatibility.
H3.onRegister 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.allRegister route handler for all HTTP methods.
const app = new H3().all("/", () => "OK");
H3.useRegister a global middleware.
const app = new H3()
.use((event) => {
console.log(`request: ${event.req.url}`);
})
.all("/", () => "OK");
H3.registerRegister a H3 plugin to extend app.
H3.handlerAn 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.mountUsing .mount method, you can register a sub-app with prefix.
H3 OptionsYou 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)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:
onErroronRequestonResponseThese 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);
},
});
H3 PropertiesH3.configGlobal H3 instance config.