Nuxt/docs/3.api/4.kit/11.nitro.md
2023-10-12 10:24:29 +01:00

7.9 KiB

title description
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

source code

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: 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

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'
    })
  }
})
export default defineEventHandler(() => {
  return {
    body: `Response generated at ${new Date().toISOString()}`
  }
})

::

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

::alert{type=warning} You can call useNitro() only after ready hook. ::

::alert{type=info} 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.

::alert{type=info} 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, 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)
    }
  }
})