Plugins can be registered either when creating a new H3 instance or by using H3.register.
import { H3 } from "h3";
import { logger } from "./logger.mjs";
// Using instance config
const app = new H3({
plugins: [logger()],
});
// Or register later
app.register(logger());
// ... rest of the code..
app.get("/**", () => "Hello, World!");
H3 plugins are simply functions that accept an H3 instance as the first argument and immediately apply logic to extend it.
app.register((app) => {
app.use(...)
})
For convenience, H3 provides a built-in definePlugin utility, which creates a typed factory function with optional plugin-specific options.
import { definePlugin } from "h3";
const logger = definePlugin((h3, _options) => {
if (h3.config.debug) {
h3.use((req) => {
console.log(`[${req.method}] ${req.url}`);
});
}
});