Configuration

Customize your Nitro app with a configuration file.

In order to customize Nitro's behavior, we create a file named nitro.config.ts.

nitro.config.ts
import { defineNitroConfig } from "nitropack/config";

export default defineNitroConfig({
  // options
});
nuxt.config.ts
export default defineNuxtConfig({
  nitro: {
    // options
  }
})

General

preset

Use preset option NITRO_PRESET environment variable for custom production preset.

Preset for development mode is always nitro-dev and default node-server for production building a standalone Node.js server.

The preset will automatically be detected when the preset option is not set and running in known environments.

logLevel

  • Default: 3 (1 when the testing environment is detected)

Log verbosity level. See unjs/consola#level for more information.

runtimeConfig

  • Default: { nitro: { ... }, ...yourOptions }

Server runtime configuration.

Note:: nitro namespace is reserved.

Features

experimental

  • Default: {}

Enable experimental features.

openAPI

Enable /_nitro/swagger and /_nitro/openapi.json endpoints.

wasm

Enable WASM support

legacyExternals

When enabled, lagacy (unstable) experimental rollup externals algorithm will be used.

future

  • Default: {}

New features pending for a major version to avoid breaking changes.

nativeSWR

Uses built-in SWR functionality (using caching layer and storage) for Netlify and Vercel presets instead of falling back to ISR behavior.

storage

  • Default: {}

Storage configuration, read more in the Storage Layer section.

timing

  • Default: false

Enable timing information:

  • Nitro startup time log
  • Server-Timing header on HTTP responses

renderer

Path to main render (file should export an event handler as default)

serveStatic

  • Type: boolean | 'node' | 'deno'
  • Default: depends of the deployment preset used.

Serve public/ assets in production.

Note: It is highly recommended that your edge CDN (nginx, apache, cloud) serves the .output/public/ directory instead to enable compression and higher lever caching.

noPublicDir

  • Default: false

If enabled, disabled .output/public directory creation. Skipping to copy public/ dir and also disables pre-renderering.

publicAssets

Public asset directories to serve in development and bundle in production.

If a public/ directory is detected, it will be added by default, but you can add more by yourself too!

It's possible to set Cache-Control headers for assets using the maxAge option:

  publicAssets: [
    {
      baseURL: "images",
      dir: "public/images",
      maxAge: 60 * 60 * 24 * 7, // 7 days
    },
  ],

The config above generates the following header in the assets under public/images/ folder:

cache-control: public, max-age=604800, immutable

compressPublicAssets

  • Default: { gzip: false, brotli: false }

If enabled, Nitro will generate a pre-compressed (gzip and/or brotli) version of supported types of public assets and prerendered routes larger than 1024 bytes into the public directory. The best compression level is used. Using this option you can support zero overhead asset compression without using a CDN.

List of compressible MIME types:

serverAssets

Assets can be accessed in server logic and bundled in production. Read more.

devServer

  • Default: { watch: [] }

Dev server options. You can use watch to make the dev server reload if any file changes in specified paths.

watchOptions

Watch options for development mode. See chokidar for more information.

imports

Auto import options. See unjs/unimport for more information.

plugins

  • Default: []

An array of paths to nitro plugins. They will be executed by order on the first initialization.

Note that Nitro auto-register the plugins in the plugins/ directory, learn more.

virtual

  • Default: {}

A map from dynamic virtual import names to their contents or an (async) function that returns it.

Routing

baseURL

Default: / (or NITRO_APP_BASE_URL environment variable if provided)

Server's main base URL.

handlers

Server handlers and routes.

If routes/, api/ or middleware/ directories exist, they will be automatically added to the handlers array.

devHandlers

Regular handlers refer to the path of handlers to be imported and transformed by rollup.

There are situations in that we directly want to provide a handler instance with programmatic usage.

We can use devHandlers but note that they are only available in development mode and not in production build.

For example:

import { defineNitroConfig } from 'nitropack/config'
import { eventHandler } from 'h3'

export default defineNitroConfig({
  devHandlers: [
    {
      route: '/',
      handler: eventHandler((event) => {
       console.log(event)
      })
    }
  ]
})
Note that eventHandler is a helper function from h3 library.

devProxy

Proxy configuration for development server.

You can use this option to override development server routes and proxy-pass requests.

{
  devProxy: {
    '/proxy/test': 'http://localhost:3001',
    '/proxy/example': { target: 'https://example.com', changeOrigin: true }
  }
}

See https://github.com/http-party/node-http-proxy#options for all available target options.

errorHandler

Path to a custom runtime error handler. Replacing nitro's built-in error page.

Example:

nitro.config
import { defineNitroConfig } from "nitropack/config";

export default defineNitroConfig({
  errorHandler: "~/error",
});
error.ts
import type { NitroErrorHandler } from 'nitropack'

export default <NitroErrorHandler> function (error, event) {
  event.res.end('[custom error handler] ' + error.stack)
}

routeRules

🧪 Experimental!

Route options. It is a map from route pattern (following unjs/radix3) to route options.

When cache option is set, handlers matching pattern will be automatically wrapped with defineCachedEventHandler.

See the Cache API for all available cache options.

swr: true|number is shortcut for cache: { swr: true, maxAge: number }

Example:

routeRules: {
  '/blog/**': { swr: true },
  '/blog/**': { swr: 600 },
  '/blog/**': { static: true },
  '/blog/**': { cache: { /* cache options*/ } },
  '/assets/**': { headers: { 'cache-control': 's-maxage=0' } },
  '/api/v1/**': { cors: true, headers: { 'access-control-allow-methods': 'GET' } },
  '/old-page': { redirect: '/new-page' }, // uses status code 307 (Temporary Redirect)
  '/old-page2': { redirect: { to:'/new-page2', statusCode: 301 } },
  '/proxy/example': { proxy: 'https://example.com' },
  '/proxy/**': { proxy: '/api/**' },
}

prerender

Default: { crawlLinks: false, ignore: [], routes: [] }

Prerendered options. Any route specified will be fetched during the build and copied to the .output/public directory as a static asset.

Any route that starts with a prefix listed in ignore will be ignored.

If crawlLinks option is set to true, nitro starts with / by default (or all routes in routes array) and for HTML pages extracts <a> tags and prerender them as well.

Directories

rootDir

Project main directory

srcDir

Project source directory. Same as rootDir unless specified. Helpful to move code into src/.

scanDirs

  • Default: (source directory when empty array)

List of directories to scan and auto-register files, such as API routes.

buildDir

  • Default: .nitro

nitro's temporary working directory for generating build-related files.

output

  • Default: { dir: '.output', serverDir: '.output/server', publicDir: '.output/public' }

Output directories for production bundle.

Advanced

dev

  • Default: true for development and false for production.

⚠️ Caution! This is an advanced configuration. things can go wrong if misconfigured.

typescript

Default: { generateTsConfig: true }

nodeModulesDirs

⚠️ Caution! This is an advanced configuration. things can go wrong if misconfigured.

Additional node_modules to search when resolving a module. By default user directory is added.

hooks

⚠️ Caution! This is an advanced configuration. things can go wrong if misconfigured.

nitro hooks. See unjs/hookable for more information.

commands

⚠️ Caution! This is an advanced configuration. things can go wrong if misconfigured.

Preview and deploy command hints are usually filled by deployment presets.

devErrorHandler

⚠️ Caution! This is an advanced configuration. things can go wrong if misconfigured.

A custom error handler function for development errors.

Rollup

rollupConfig

Additional rollup configuration.

entry

Rollup entry.

unenv

Options for unjs/unenv preset.

alias

Rollup aliases options.

minify

  • Default: false

Minify bundle.

inlineDynamicImports

Avoid creating chunks.

sourceMap

Enable source-map generation. See options

  • Default: true

node

Specify whether the build is used for Node.js or not. If set to false, nitro tried to mock Node.js dependencies using unjs/unenv and adjust its behavior.

analyze

If enabled, will analyze server bundle after build using rollup-plugin-visualizer. You can also pass your custom options.

moduleSideEffects

Default: ['unenv/runtime/polyfill/', 'node-fetch-native/polyfill']

Rollup specific option. Specifies module imports that have side-effects

replace

Rollup specific option.

commonJS

Rollup specific option. Specifies additional configuration for the rollup CommonJS plugin.