--- icon: ri:plug-line --- # Plugins > Use runtime plugins to extend Nitro's runtime behavior. Runtime plugins are **executed once** during server startup, making them the right place for one-time initialization and for registering [lifecycle hooks](/docs/lifecycle). Each plugin receives the `nitroApp` context. Plugins are auto-registered from the `plugins/` directory and run in order. A plugin can also be [async](#async-plugins). ```ts [plugins/test.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { console.log('Nitro plugin', nitroApp) }) ``` If you have plugins in another directory, you can use the `plugins` option: ```ts [nitro.config.ts] import { defineConfig } from "nitro"; export default defineConfig({ plugins: ['my-plugins/hello.ts'] }) ``` Plugins run in this order: 1. Plugins listed in the `plugins` option, in the order they are listed. 2. Plugins auto-registered from `plugins/` directories. Directories are processed in [`scanDirs`](/config/directories#scandirs) order, and files within each directory are sorted by path. ## Async plugins A plugin can return a promise, for example to connect to a database before the server handles traffic: ```ts [plugins/db.ts] import { definePlugin } from "nitro"; export default definePlugin(async (nitroApp) => { const db = await connectToDatabase(); nitroApp.hooks.hook("close", () => db.close()); }); ``` The plugins after an async plugin run once it resolves, so they can rely on what it set up. Until all plugins have finished: - Incoming requests are held and handled once initialization completes. - Platform events dispatched as hooks (such as `cloudflare:scheduled` or `cloudflare:queue`) and scheduled tasks are deferred as well. - `nitroApp.ready` is a promise that resolves when initialization completes. It is `undefined` once the app is ready. This does not rely on top-level `await`, so it works on every deployment target. Once all plugins have resolved, requests are handled without any extra overhead. If a plugin rejects, the plugins after it do not run. The error is passed to the `error` hook and reported as an unhandled rejection (like an error thrown by a sync plugin), and requests fail with a `500` response from then on. ::warning Do not `await` a request to the app itself (such as `fetch("/api/...")`) inside an async plugin: requests are held until the plugin resolves, so it would never complete. :: ::note Platforms such as Cloudflare Workers do not allow I/O (like `fetch()` or opening sockets) outside of a request. Plugins run at startup, so on these platforms set up connections lazily (on first use) instead. :: ## The `nitroApp` context The plugin function receives a `nitroApp` object with the following properties: | Property | Type | Description | | --- | --- | --- | | `hooks` | [`HookableCore`](https://github.com/unjs/hookable) | Hook system for registering lifecycle callbacks. | | `h3` | `H3Core` | The underlying [H3](https://github.com/h3js/h3) application instance. | | `fetch` | `(req: Request) => Response \| Promise` | The app's internal fetch handler. | | `captureError` | `(error: Error, context) => void` | Programmatically capture errors into the error hook pipeline. | | `ready` | `Promise \| undefined` | Set while [async plugins](#async-plugins) are initializing. | ::note H3 composes the middleware chain once, on the first request. Middleware a plugin adds to `nitroApp.h3["~middleware"]` during startup is included, but it runs before Nitro's route rules when placed at the front of the array. If a plugin changes the array after the first request was handled, it must also reset `nitroApp.h3["~dispatch"]` and `nitroApp.h3["~composed"]` to `undefined` so the chain is recomposed. :: ## Nitro runtime hooks Use Nitro [hooks](https://github.com/unjs/hookable) to run custom functions at specific points in the [request lifecycle](/docs/lifecycle). Register them inside plugins with `nitroApp.hooks.hook()`: ```ts [plugins/close.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.hooks.hook("close", async () => { // Will run when nitro is being closed }); }) ``` ### Available hooks | Hook | Signature | Description | | --- | --- | --- | | `request` | `(event: HTTPEvent) => void \| Promise` | Called at the start of each request. | | `response` | `(res: Response, event: HTTPEvent) => void \| Promise` | Called after the response is created. | | `error` | `(error: Error, context: { event?: HTTPEvent, tags?: string[] }) => void` | Called when an error is captured. | | `shutdown` | `(ctx: { waitUntil, signal }) => void \| Promise` | Called when the server starts shutting down, to finish work in progress (`node_server`, `node_cluster`, `bun` and `deno_server` presets). | | `close` | `() => void` | Called when the Nitro server is shutting down, to clean up resources (after `shutdown`). | > [!NOTE] > The `NitroRuntimeHooks` interface is augmentable. Deployment presets (such as Cloudflare) can extend it with platform-specific hooks like `cloudflare:scheduled` and `cloudflare:email`. ### Unregistering hooks The `hook()` method returns an unregister function that can be called to remove the hook: ```ts [plugins/example.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { const unregister = nitroApp.hooks.hook("request", (event) => { // ... }); // Later, remove the hook unregister(); }); ``` ## Examples ### Capturing errors You can use plugins to capture all application errors. ```ts [plugins/errors.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.hooks.hook("error", async (error, { event }) => { console.error(`${event?.req.url} Application error:`, error) }); }) ``` The `context` object includes an optional `tags` array that identifies the error source (e.g., `"request"`, `"response"`, `"cache"`, `"plugin"`, `"unhandledRejection"`, `"uncaughtException"`). ### Programmatic error capture You can use `captureError` to manually feed errors into the error hook pipeline: ```ts [plugins/capture.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.captureError(new Error("something went wrong"), { tags: ["startup"], }); }); ``` ### Graceful shutdown The server shuts down gracefully, waiting for any pending background tasks started with `event.waitUntil`. Use the [`shutdown` hook](/docs/lifecycle#server-shutdown) to finish work in progress, and the `close` hook to clean up your own resources: ```ts [plugins/shutdown.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.hooks.hook("close", async () => { // Clean up resources, close connections, etc. }); }); ``` ### Request and response lifecycle You can use plugins to register hooks that run on the [request lifecycle](/docs/lifecycle): ```ts [plugins/lifecycle.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.hooks.hook("request", (event) => { console.log("on request", event.req.url); }); nitroApp.hooks.hook("response", (res, event) => { // Modify or inspect the response console.log("on response", res.status); }); }); ``` ### Modifying response headers ```ts [plugins/headers.ts] import { definePlugin } from "nitro"; export default definePlugin((nitroApp) => { nitroApp.hooks.hook("response", (res, event) => { const { pathname } = new URL(event.req.url); if (pathname.endsWith(".css") || pathname.endsWith(".js")) { res.headers.append("Vary", "Origin"); } }); }); ```