Plugins

Use plugins to extend Nitro's runtime behavior.
Nitro v3 Alpha docs are a work in progress — expect updates, rough edges, and occasional inaccuracies.

Nitro plugins will be executed once during server startup in order to allow extending Nitro's runtime behavior. They receive nitroApp context, which can be used to hook into Nitro lifecycle events.

Plugins are auto-registered from plugins/ directory and run synchronously (by order of file name) on the first Nitro initialization.

Example:

plugins/test.ts
export default defineNitroPlugin((nitroApp) => {
  console.log('Nitro plugin', nitroApp)
})

If you have plugins in another directory, you can use the plugins option:

nitro.config.ts
import { defineNitroConfig } from "nitro/config";

export default defineNitroConfig({
  plugins: ['my-plugins/hello.ts']
})

Nitro runtime hooks

You can use Nitro hooks to extend the default runtime behaviour of Nitro by registering custom (async or sync) functions to the lifecycle events within plugins.

Example:

export default defineNitroPlugin((nitro) => {
  nitro.hooks.hook("close", async () => {
    // Will run when nitro is being closed
  });
})

Available hooks

See the source code for list of all available runtime hooks.

  • "close", () => {}
  • "error", (error, { event? }) => {}
  • "render:response", (response, { event }) => {}
  • "request", (event) => {}
  • "beforeResponse", (event, { body }) => {}
  • "afterResponse", (event, { body }) => {}

Examples

Capturing errors

You can use plugins to capture all application errors.

export default defineNitroPlugin((nitro) => {
  nitro.hooks.hook("error", async (error, { event }) => {
    console.error(`${event.path} Application error:`, error)
  });
})

Graceful shutdown

You can use plugins to register a hook that resolves when Nitro is closed.

export default defineNitroPlugin((nitro) => {
  nitro.hooks.hookOnce("close", async () => {
    // Will run when nitro is closed
    console.log("Closing nitro server...")
    await new Promise((resolve) => setTimeout(resolve, 500));
    console.log("Task is done!");
  });
})

Request and response lifecycle

You can use plugins to register a hook that can run on request lifecycle:

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook("request", (req) => {
    console.log("on request", req.url);
  });

  nitroApp.hooks.hook("beforeResponse", (event, { body }) => {
    console.log("on response", event.path, { body });
  });

  nitroApp.hooks.hook("afterResponse", (event, { body }) => {
    console.log("on after response", event.path, { body });
  });
});