Nitro is an open source TypeScript framework to build ultra-fast web servers. Nuxt 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.
addServerHandlerAdds a Nitro server handler. Use this if you want to create server middleware or a custom route.
twoslash
export default defineNuxtModule({
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerHandler({
route: '/robots.txt',
handler: resolve('./runtime/robots.get'),
})
},
})function addServerHandler (handler: NitroEventHandler): voidhandler: 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 and should normally return nothing to pass to the next handlers. |
lazy | boolean | false | Use lazy loading to import the handler. This is useful when you only want to load the handler on demand. |
method | string | false | Router method matcher. If handler name contains method name, it will be used as a default value. |
You can use addServerHandler to add a server handler from your module.
export default defineNuxtModule({
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerHandler({
route: '/robots.txt',
handler: resolve('./runtime/robots.get'),
})
},
})When you access /robots.txt, it will return the following response:
User-agent: *
Disallow: /addDevServerHandlerAdds a Nitro server handler to be used only in development mode. This handler will be excluded from production build.
twoslash
export default defineNuxtModule({
setup () {
addDevServerHandler({
handler: defineEventHandler(() => {
return {
body: `Response generated at ${new Date().toISOString()}`,
}
}),
route: '/_handler',
})
},
})twoslash
// @errors: 2391
// ---cut---
function addDevServerHandler (handler: NitroDevEventHandler): voidhandler: 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. |
In some cases, you may want to create a server handler specifically for development purposes, such as a Tailwind config viewer.
export default defineNuxtModule({
async setup (options, nuxt) {
const route = joinURL(nuxt.options.app?.baseURL, '/_tailwind')
// @ts-expect-error - tailwind-config-viewer does not have correct types
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 })
},
})useNitroReturns the Nitro instance.
useNitro() only after ready hook.
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
nuxt.hook('ready', () => {
const nitro = useNitro()
// Do something with Nitro instance
})
},
})function useNitro (): NitroaddServerPluginAdd plugin to extend Nitro's runtime behavior.
defineNitroPlugin from nitropack/runtime within your plugin file. The same requirement applies to utilities such as useRuntimeConfig.twoslash
export default defineNuxtModule({
setup () {
const { resolve } = createResolver(import.meta.url)
addServerPlugin(resolve('./runtime/plugin.ts'))
},
})function addServerPlugin (plugin: string): void| 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. |
export default defineNuxtModule({
setup () {
const { resolve } = createResolver(import.meta.url)
addServerPlugin(resolve('./runtime/plugin.ts'))
},
})addPrerenderRoutesAdd routes to be prerendered to Nitro.
export default defineNuxtModule({
meta: {
name: 'nuxt-sitemap',
configKey: 'sitemap',
},
defaults: {
sitemapUrl: '/sitemap.xml',
prerender: true,
},
setup (options) {
if (options.prerender) {
addPrerenderRoutes(options.sitemapUrl)
}
},
})function addPrerenderRoutes (routes: string | string[]): void| Property | Type | Required | Description |
|---|
addServerImportsAdd imports to the server. It makes your imports available in Nitro without the need to import them manually.
shared/ directory, the function must be imported from the same source file for both addImports and addServerImports and should have identical signature. That source file should not import anything context-specific (i.e., Nitro context, Nuxt app context) or else it might cause errors during type-checking.twoslash
export default defineNuxtModule({
setup (options) {
const names = [
'useStoryblok',
'useStoryblokApi',
'useStoryblokBridge',
'renderRichText',
'RichTextSchema',
]
names.forEach(name =>
addServerImports({ name, as: name, from: '@storyblok/vue' }),
)
},
})function addServerImports (dirs: Import | Import[]): voidimports: 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; if multiple imports have the same name, the one with the highest priority will be used. |
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. |
addServerImportsDirAdd a directory to be scanned for auto-imports by Nitro.
twoslash
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule',
},
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerImportsDir(resolve('./runtime/server/composables'))
},
})function addServerImportsDir (dirs: string | string[], opts: { prepend?: boolean }): void| Property | Type | Required | Description |
|---|---|---|---|
opts | { prepend?: boolean } | false | Options for the import directory. If prepend is true, the directory is added to the beginning of the scan list. |
You can use addServerImportsDir to add a directory to be scanned by Nitro. This is useful when you want Nitro to auto-import functions from a custom server directory.
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule',
},
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerImportsDir(resolve('./runtime/server/composables'))
},
})You can then use the useApiSecret function in your server code:
const useApiSecret = (): string => ''
// ---cut---
export default defineEventHandler(() => {
const apiSecret = useApiSecret()
// Do something with the apiSecret
})addServerScanDirAdd directories to be scanned by Nitro. It will check for subdirectories, which will be registered just like the ~~/server folder is.
~~/server/api, ~~/server/routes, ~~/server/middleware, and ~~/server/utils are scanned.twoslash
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule',
},
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerScanDir(resolve('./runtime/server'))
},
})function addServerScanDir (dirs: string | string[], opts: { prepend?: boolean }): void| Property | Type | Required | Description |
|---|---|---|---|
opts | { prepend?: boolean } | false | Options for the import directory. If prepend is true, the directory is added to the beginning of the scan list. |
You can use addServerScanDir to add a directory to be scanned by Nitro. This is useful when you want to add a custom server directory.
export default defineNuxtModule({
meta: {
name: 'my-module',
configKey: 'myModule',
},
setup (options) {
const { resolve } = createResolver(import.meta.url)
addServerScanDir(resolve('./runtime/server'))
},
})You can then use the hello function in your server code.
function hello () {
return 'Hello from server utils!'
}
// ---cut---
export default defineEventHandler(() => {
return hello() // Hello from server utils!
})