> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/nuxt/nuxt/llms.txt
> Use this file to discover all available pages before exploring further.

# Nitro

> Nitro utilities to add server handlers, plugins, and prerender routes

# Nitro

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.

Nitro is an open source TypeScript framework to build ultra-fast web servers. Nuxt uses Nitro as its server engine.

## `addServerHandler`

Adds a Nitro server handler. Use this if you want to create server middleware or a custom route.

### Type

```ts theme={null}
function addServerHandler(handler: NitroEventHandler): void
```

### Parameters

**`handler`**: A handler object with the following properties:

| Property     | Type      | Required | Description                                                                              |
| ------------ | --------- | -------- | ---------------------------------------------------------------------------------------- |
| `handler`    | `string`  | `true`   | Path to event handler.                                                                   |
| `route`      | `string`  | `false`  | Path prefix or route. If an empty string used, will be used as a middleware.             |
| `middleware` | `boolean` | `false`  | Specifies this is a middleware handler. Middleware are called on every route.            |
| `lazy`       | `boolean` | `false`  | Use lazy loading to import the handler.                                                  |
| `method`     | `string`  | `false`  | Router method matcher. If handler name contains method name, it will be used as default. |

### Usage

```ts theme={null}
import { addServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const { resolve } = createResolver(import.meta.url)

    addServerHandler({
      route: '/robots.txt',
      handler: resolve('./runtime/robots.get'),
    })
  },
})
```

## `addDevServerHandler`

Adds a Nitro server handler to be used only in development mode. This handler will be excluded from production build.

### Type

```ts theme={null}
function addDevServerHandler(handler: NitroDevEventHandler): void
```

### Parameters

**`handler`**: A handler object with the following properties:

| Property  | Type           | Required | Description                                                                  |
| --------- | -------------- | -------- | ---------------------------------------------------------------------------- |
| `handler` | `EventHandler` | `true`   | Event handler.                                                               |
| `route`   | `string`       | `false`  | Path prefix or route. If an empty string used, will be used as a middleware. |

### Usage

```ts theme={null}
import { defineEventHandler } from 'h3'
import { addDevServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    addDevServerHandler({
      handler: defineEventHandler(() => {
        return {
          body: `Response generated at ${new Date().toISOString()}`,
        }
      }),
      route: '/_handler',
    })
  },
})
```

## `useNitro`

Returns the Nitro instance.

**Warning:** You can call `useNitro()` only after `ready` hook.

**Note:** Changes to the Nitro instance configuration are not applied.

### Type

```ts theme={null}
function useNitro(): Nitro
```

### Usage

```ts theme={null}
import { defineNuxtModule, useNitro } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options, nuxt) {
    nuxt.hook('ready', () => {
      const nitro = useNitro()
      // Do something with Nitro instance
    })
  },
})
```

## `addServerPlugin`

Add plugin to extend Nitro's runtime behavior.

**Warning:** It is necessary to explicitly import `defineNitroPlugin` from `nitropack/runtime` within your plugin file.

### Type

```ts theme={null}
function addServerPlugin(plugin: string): void
```

### Parameters

| Property | Type     | Required | Description                                                                                                   |
| -------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `plugin` | `string` | `true`   | Path to the plugin. The plugin must export a default function that accepts the Nitro instance as an argument. |

### Usage

```ts theme={null}
import { addServerPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    const { resolve } = createResolver(import.meta.url)
    addServerPlugin(resolve('./runtime/plugin.ts'))
  },
})
```

Runtime plugin example:

```ts theme={null}
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 })
  })
})
```

## `addPrerenderRoutes`

Add routes to be prerendered to Nitro.

### Type

```ts theme={null}
function addPrerenderRoutes(routes: string | string[]): void
```

### Parameters

| Property | Type                 | Required | Description                                 |
| -------- | -------------------- | -------- | ------------------------------------------- |
| `routes` | `string \| string[]` | `true`   | A route or an array of routes to prerender. |

### Usage

```ts theme={null}
import { addPrerenderRoutes, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  meta: {
    name: 'nuxt-sitemap',
    configKey: 'sitemap',
  },
  defaults: {
    sitemapUrl: '/sitemap.xml',
    prerender: true,
  },
  setup(options) {
    if (options.prerender) {
      addPrerenderRoutes(options.sitemapUrl)
    }
  },
})
```

## `addServerImports`

Add imports to the server. It makes your imports available in Nitro without the need to import them manually.

### Type

```ts theme={null}
function addServerImports(dirs: Import | Import[]): void
```

### Parameters

**`imports`**: An object or an array of objects with the following properties:

| Property   | Type                  | Required | Description                                                     |
| ---------- | --------------------- | -------- | --------------------------------------------------------------- |
| `name`     | `string`              | `true`   | Import name to be detected.                                     |
| `from`     | `string`              | `true`   | Module specifier to import from.                                |
| `priority` | `number`              | `false`  | Priority of the import.                                         |
| `disabled` | `boolean`             | `false`  | If this import is disabled.                                     |
| `meta`     | `Record<string, any>` | `false`  | Metadata of the import.                                         |
| `type`     | `boolean`             | `false`  | If this import is a pure type import.                           |
| `typeFrom` | `string`              | `false`  | Use this as the `from` value when generating type declarations. |
| `as`       | `string`              | `false`  | Import as this name.                                            |

### Usage

```ts theme={null}
import { addServerImports, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const names = [
      'useStoryblok',
      'useStoryblokApi',
      'useStoryblokBridge',
      'renderRichText',
      'RichTextSchema',
    ]

    names.forEach(name =>
      addServerImports({ name, as: name, from: '@storyblok/vue' })
    )
  },
})
```

## `addServerImportsDir`

Add a directory to be scanned for auto-imports by Nitro.

### Type

```ts theme={null}
function addServerImportsDir(dirs: string | string[], opts: { prepend?: boolean }): void
```

### Parameters

| Property | Type                    | Required | Description                                                                       |
| -------- | ----------------------- | -------- | --------------------------------------------------------------------------------- |
| `dirs`   | `string \| string[]`    | `true`   | A directory or an array of directories to register to be scanned by Nitro.        |
| `opts`   | `{ prepend?: boolean }` | `false`  | If `prepend` is `true`, the directory is added to the beginning of the scan list. |

### Usage

```ts theme={null}
import { addServerImportsDir, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const { resolve } = createResolver(import.meta.url)
    addServerImportsDir(resolve('./runtime/server/composables'))
  },
})
```

## `addServerScanDir`

Add directories to be scanned by Nitro. It will check for subdirectories, which will be registered just like the `~~/server` folder is.

**Note:** Only `~~/server/api`, `~~/server/routes`, `~~/server/middleware`, and `~~/server/utils` are scanned.

### Type

```ts theme={null}
function addServerScanDir(dirs: string | string[], opts: { prepend?: boolean }): void
```

### Parameters

| Property | Type                    | Required | Description                                                                               |
| -------- | ----------------------- | -------- | ----------------------------------------------------------------------------------------- |
| `dirs`   | `string \| string[]`    | `true`   | A directory or an array of directories to register to be scanned by Nitro as server dirs. |
| `opts`   | `{ prepend?: boolean }` | `false`  | If `prepend` is `true`, the directory is added to the beginning of the scan list.         |

### Usage

```ts theme={null}
import { addServerScanDir, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options) {
    const { resolve } = createResolver(import.meta.url)
    addServerScanDir(resolve('./runtime/server'))
  },
})
```

## Source

[View source on GitHub](https://github.com/nuxt/nuxt/blob/main/packages/kit/src/nitro.ts)
