Nuxt/docs/3.api/5.kit/11.nitro.md
Sébastien Chopin f26a801775
docs: update to new website (#23743)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
2023-10-18 12:59:43 +02:00

361 lines
8.0 KiB
Markdown

---
title: "Nitro"
description: Nuxt Kit provides a set of utilities to help you work with Nitro. These functions allow you to add server handlers, plugins, and prerender routes.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/kit/src/nitro.ts
size: xs
---
Nitro is an open source TypeScript framework to build ultra-fast web servers. Nuxt 3 (and, optionally, Nuxt Bridge) uses Nitro as its server engine. You can use `useNitro` to access the Nitro instance, `addServerHandler` to add a server handler, `addDevServerHandler` to add a server handler to be used only in development mode, `addServerPlugin` to add a plugin to extend Nitro's runtime behavior, and `addPrerenderRoutes` to add routes to be prerendered by Nitro.
## `addServerHandler`
Adds a nitro server handler. Use it if you want to create server middleware or custom route.
### Type
```ts
function addServerHandler (handler: NitroEventHandler): void
export interface NitroEventHandler {
handler: string;
route?: string;
middleware?: boolean;
lazy?: boolean;
method?: string;
}
```
### Parameters
#### `handler`
**Type**: `NitroEventHandler`
**Required**: `true`
A handler object with the following properties:
- `handler` (required)
**Type**: `string`
Path to event handler.
- `route` (optional)
**Type**: `string`
Path prefix or route. If an empty string used, will be used as a middleware.
- `middleware` (optional)
**Type**: `boolean`
Specifies this is a middleware handler. Middleware are called on every route and should normally return nothing to pass to the next handlers.
- `lazy` (optional)
**Type**: `boolean`
Use lazy loading to import handler.
- `method` (optional)
**Type**: `string`
Router method matcher. If handler name contains method name, it will be used as a default value.
### Examples
::code-group
```ts [module.ts]
// https://github.com/nuxt-modules/robots
import { createResolver, defineNuxtModule, addServerHandler } from '@nuxt/kit'
export default defineNuxtModule({
setup(options) {
const resolver = createResolver(import.meta.url)
addServerHandler({
route: '/robots.txt'
handler: resolver.resolve('./runtime/robots.get.ts')
})
}
})
```
```ts [runtime/robots.get.ts]
export default defineEventHandler(() => {
return {
body: `User-agent: *\nDisallow: /`
}
})
```
::
## `addDevServerHandler`
Adds a nitro server handler to be used only in development mode. This handler will be excluded from production build.
### Type
```ts
function addDevServerHandler (handler: NitroEventHandler): void
export interface NitroEventHandler {
handler: string;
route?: string;
middleware?: boolean;
lazy?: boolean;
method?: string;
}
```
### Parameters
#### `handler`
**Type**: `NitroEventHandler`
**Required**: `true`
A handler object with the following properties:
- `handler` (required)
**Type**: `string`
Path to event handler.
- `route` (optional)
**Type**: `string`
Path prefix or route. If an empty string used, will be used as a middleware.
- `middleware` (optional)
**Type**: `boolean`
Specifies this is a middleware handler. Middleware are called on every route and should normally return nothing to pass to the next handlers.
- `lazy` (optional)
**Type**: `boolean`
Use lazy loading to import handler.
- `method` (optional)
**Type**: `string`
Router method matcher.
### Examples
::code-group
```ts [module.ts]
import { createResolver, defineNuxtModule, addDevServerHandler } from '@nuxt/kit'
export default defineNuxtModule({
setup() {
const resolver = createResolver(import.meta.url)
addDevServerHandler({
handler: resolver.resolve('./runtime/uptime.get'),
route: '/_handler'
})
}
})
```
```ts [runtime/timer.get.ts]
export default defineEventHandler(() => {
return {
body: `Response generated at ${new Date().toISOString()}`
}
})
```
::
```ts
// https://github.com/nuxt-modules/tailwindcss
import { joinURL } from 'ufo'
import { defineNuxtModule, addDevServerHandler } from '@nuxt/kit'
export default defineNuxtModule({
async setup(options) {
const route = joinURL(nuxt.options.app?.baseURL, '/_tailwind')
// @ts-ignore
const createServer = await import('tailwind-config-viewer/server/index.js').then(r => r.default || r) as any
const viewerDevMiddleware = createServer({ tailwindConfigProvider: () => options, routerPrefix: route }).asMiddleware()
addDevServerHandler({ route, handler: viewerDevMiddleware })
}
})
```
## `useNitro`
Returns the Nitro instance.
::callout{color="amber" icon="i-ph-warning-duotone"}
You can call `useNitro()` only after `ready` hook.
::
::callout
Changes to the Nitro instance configuration are not applied.
::
### Type
```ts
function useNitro (): Nitro
export interface Nitro {
options: NitroOptions;
scannedHandlers: NitroEventHandler[];
vfs: Record<string, string>;
hooks: Hookable<NitroHooks>;
unimport?: Unimport;
logger: ConsolaInstance;
storage: Storage;
close: () => Promise<void>;
updateConfig: (config: NitroDynamicConfig) => void | Promise<void>;
}
```
### Examples
```ts
// https://github.com/nuxt/nuxt/blob/4e05650cde31ca73be4d14b1f0d23c7854008749/packages/nuxt/src/core/nuxt.ts#L404
import { defineNuxtModule, useNitro, addPlugin, createResolver } from '@nuxt/kit'
export default defineNuxtModule({
setup(options, nuxt) {
const resolver = createResolver(import.meta.url)
nuxt.hook('ready', () => {
const nitro = useNitro()
if (nitro.options.static && nuxt.options.experimental.payloadExtraction === undefined) {
console.warn('Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.')
nuxt.options.experimental.payloadExtraction = true
}
nitro.options.replace['process.env.NUXT_PAYLOAD_EXTRACTION'] = String(!!nuxt.options.experimental.payloadExtraction)
nitro.options._config.replace!['process.env.NUXT_PAYLOAD_EXTRACTION'] = String(!!nuxt.options.experimental.payloadExtraction)
if (!nuxt.options.dev && nuxt.options.experimental.payloadExtraction) {
addPlugin(resolver.resolve(nuxt.options.appDir, 'plugins/payload.client'))
}
})
}
})
```
## `addServerPlugin`
Add plugin to extend Nitro's runtime behavior.
::callout
You can read more about Nitro plugins in the [Nitro documentation](https://nitro.unjs.io/guide/plugins).
::
### Type
```ts
function addServerPlugin (plugin: string): void
```
### Parameters
#### `plugin`
**Type**: `string`
**Required**: `true`
Path to the plugin. The plugin must export a function that accepts Nitro instance as an argument.
### Examples
::code-group
```ts [module.ts]
import { createResolver, defineNuxtModule, addServerPlugin } from '@nuxt/kit'
export default defineNuxtModule({
setup() {
const resolver = createResolver(import.meta.url)
addServerPlugin(resolver.resolve('./runtime/plugin.ts'))
}
})
```
```ts [runtime/plugin.ts]
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook("request", (event) => {
console.log("on request", event.path);
});
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 });
});
});
```
::
## `addPrerenderRoutes`
Add routes to be prerendered to Nitro.
### Type
```ts
function function addPrerenderRoutes (routes: string | string[]): void
```
### Parameters
#### `routes`
**Type**: `string | string[]`
**Required**: `true`
A route or an array of routes to prerender.
### Examples
```ts
import { defineNuxtModule, prerenderRoutes } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'nuxt-sitemap',
configKey: 'sitemap',
},
defaults: {
sitemapUrl: '/sitemap.xml',
prerender: true,
},
setup(options) {
if (options.prerender) {
prerenderRoutes(options.sitemapUrl)
}
}
})
```