Nuxt/docs/3.api/5.kit/11.nitro.md
2024-02-21 18:09:45 +01:00

8.9 KiB

title description links
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.
label icon to size
Source i-simple-icons-github https://github.com/nuxt/nuxt/blob/main/packages/kit/src/nitro.ts 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

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

// 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')
    })
  }
})
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

function addDevServerHandler (handler: NitroDevEventHandler): void

export interface NitroDevEventHandler {
  handler: EventHandler;
  route?: string;
}

Parameters

handler

Type: NitroEventHandler

Required: true

A handler object with the following properties:

  • handler (required)

    Type: string

    The event handler.

  • route (optional)

    Type: string

    Path prefix or route. If an empty string used, will be used as a middleware.

Examples

::code-group

import { createResolver, defineNuxtModule, addDevServerHandler } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url)

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

::

// 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.

::warning You can call useNitro() only after ready hook. ::

::note Changes to the Nitro instance configuration are not applied. ::

Type

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

// 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.

::tip You can read more about Nitro plugins in the Nitro documentation. ::

Type

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

import { createResolver, defineNuxtModule, addServerPlugin } from '@nuxt/kit'

export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url)
    addServerPlugin(resolver.resolve('./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

function function addPrerenderRoutes (routes: string | string[]): void

Parameters

routes

Type: string | string[]

Required: true

A route or an array of routes to prerender.

Examples

import { defineNuxtModule, addPrerenderRoutes } 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)
    }
  }
})

addServerImportsDir

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

Type

function addServerImportsDir (dirs: string | string[], opts: { prepend?: boolean }): void

Parameters

dirs

Type: string | string[]

Required: true

A directory or an array of directories to register to be scanned by Nitro

Examples

import { defineNuxtModule, createResolver, addServerImportsDir } from '@nuxt/kit'

export default defineNuxtModule({
  meta: {
    name: 'my-module',
    configKey: 'myModule',
  },
  setup(options) {
    const resolver = createResolver(import.meta.url)
    addServerImportsDir(resolver.resolve('./runtime/server/utils'))
  }
})

addServerScanDir

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

Type

function addServerScanDir (dirs: string | string[], opts: { prepend?: boolean }): void

Parameters

dirs

Type: string | string[]

Required: true

A directory or an array of directories to register to be scanned for by Nitro as server dirs.

Examples

import { defineNuxtModule, createResolver, addServerScanDir } from '@nuxt/kit'
export default defineNuxtModule({
  meta: {
    name: 'my-module',
    configKey: 'myModule',
  },
  setup(options) {
    const resolver = createResolver(import.meta.url)
    addServerScanDir(resolver.resolve('./runtime/server'))
  }
})