Plugins
Use plugins to extend Nitro's runtime behavior.
Plugins are auto-registered (filename ordering) and run synchronously on the first nitro initialization. They receive nitroApp
context, which can be used to hook into lifecycle events.
Scanning pattern: plugins/**/*.{ts,mjs,js,cjs}
You can order the plugins by prefixing them with a number:
plugins/
1.first.ts
2.second.ts
Example: Simple plugin
// 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 'nitropack/config'
export default defineNitroConfig({
plugins: ['my-plugins/hello.ts']
})
Examples
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!");
});
})
Renderer Response
You can use plugins to register a hook that modifies the renderer response.
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook('render:response', (response) => {
// Inspect or Modify the renderer response here
console.log(response)
})
})