Nitro logoNitro

Config

Read more in Guide > Configuration.

General

preset

Use preset option or 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.

debug

  • Default: false (true when DEBUG environment variable is set)

Enable debug mode for verbose logging and additional development information.

logLevel

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

Log verbosity level. See consola for more information.

runtimeConfig

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

Server runtime configuration.

Note: nitro namespace is reserved.

compatibilityDate

Deployment providers introduce new features that Nitro presets can leverage, but some of them need to be explicitly opted into.

Set it to latest tested date in YYYY-MM-DD format to leverage latest preset features.

If this configuration is not provided, Nitro will use "latest" behavior by default.

static

  • Default: false

Enable static site generation mode.

Features

features

  • Default: {}

Enable built-in features.

runtimeHooks

  • Default: auto-detected (enabled if there is at least one nitro plugin)

Enable runtime hooks for request and response.

websocket

  • Default: false

Enable WebSocket support.

experimental

  • Default: {}

Enable experimental features.

openAPI

  • Default: false

Enable /_scalar, /_swagger and /_openapi.json endpoints.

Prefer using the top-level openAPI option for configuration.

typescriptBundlerResolution

Enable TypeScript bundler module resolution. See TypeScript#51669.

asyncContext

Enable native async context support for useRequest().

sourcemapMinify

Set to false to disable experimental sourcemap minification.

envExpansion

Allow env expansion in runtime config. See #2043.

database

Enable experimental database support. See Database.

tasks

Enable experimental tasks support. See Tasks.

tsconfigPaths

  • Default: true

Infer path aliases from tsconfig.json.

openAPI

Top-level OpenAPI configuration.

You can pass an object to modify your OpenAPI specification:

openAPI: {
  meta: {
    title: 'My Awesome Project',
    description: 'This might become the next big thing.',
    version: '1.0'
  }
}

These routes are disabled by default in production. To enable them, use the production key. "runtime" allows middleware usage, and "prerender" is the most efficient because the JSON response is constant.

openAPI: {
    // IMPORTANT: make sure to protect OpenAPI routes if necessary!
    production: "runtime", // or "prerender"
}

If you like to customize the Scalar integration, you can pass a configuration object like this:

openAPI: {
  ui: {
    scalar: {
      theme: 'purple'
    }
  }
}

Or if you want to customize the endpoints:

openAPI: {
  route: "/_docs/openapi.json",
  ui: {
    scalar: {
      route: "/_docs/scalar"
    },
    swagger: {
      route: "/_docs/swagger"
    }
  }
}

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.

devStorage

  • Default: {}

Storage configuration overrides for development mode.

database

Database connection configurations. Requires experimental.database: true.

database: {
  default: {
    connector: "sqlite",
    options: { name: "db" }
  }
}

devDatabase

Database connection configuration overrides for development mode.

renderer

  • Type: false | { handler?: string, static?: boolean, template?: string }

Points to main render entry (file should export an event handler as default).

serveStatic

  • Type: boolean | 'node' | 'deno' | 'inline'
  • Default: depends on 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 level caching.

noPublicDir

  • Default: false

If enabled, disables .output/public directory creation. Skips copying public/ dir and also disables pre-rendering.

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

The dir option is where your files live on your file system; the baseURL option is the folder they will be accessible from when served/bundled.

compressPublicAssets

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

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

serverAssets

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

modules

  • Default: []

An array of Nitro modules. Modules can be a string (path), a module object with a setup function, or a function.

plugins

  • Default: []

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

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

tasks

  • Default: {}

Task definitions. Each key is a task name with a handler path and optional description.

tasks: {
  'db:migrate': {
    handler: './tasks/db-migrate',
    description: 'Run database migrations'
  }
}

scheduledTasks

  • Default: {}

Map of cron expressions to task name(s).

scheduledTasks: {
  '0 * * * *': 'cleanup:temp',
  '*/5 * * * *': ['health:check', 'metrics:collect']
}

imports

  • Default: false

Auto import options. Set to an object to enable. See unimport for more information.

virtual

  • Default: {}

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

ignore

  • Default: []

Array of glob patterns to ignore when scanning directories.

wasm

  • Default: {}
  • Type: false | UnwasmPluginOptions

WASM support configuration. See unwasm for options.

Dev

devServer

  • Default: { watch: [] }

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

Supports port, hostname, watch, and runner options.

watchOptions

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

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 httpxy for all available target options.

Logging

logging

  • Default: { compressedSizes: true, buildSuccess: true }

Control build logging behavior. Set compressedSizes to false to skip reporting compressed bundle sizes. Set buildSuccess to false to suppress the build success message.

Routing

baseURL

Default: / (or NITRO_APP_BASE_URL environment variable if provided)

Server's main base URL.

apiBaseURL

  • Default: /api

Changes the default API base URL prefix.

handlers

Server handlers and routes.

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

devHandlers

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

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.

routes

  • Default: {}

Inline route definitions. A map from route pattern to handler path or handler options.

errorHandler

  • Type: string | string[]

Path(s) to custom runtime error handler(s). Replaces nitro's built-in error page.

Example:

import { defineNitroConfig } from "nitro/config";

export default defineNitroConfig({
  errorHandler: "~/error",
});

routeRules

🧪 Experimental!

Route options. It is a map from route pattern (following rou3) 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 } },
  '/old-page/**': { redirect: '/new-page/**' },
  '/proxy/example': { proxy: 'https://example.com' },
  '/proxy/**': { proxy: '/api/**' },
  '/admin/**': { basicAuth: { username: 'admin', password: 'secret' } },
}

prerender

Default:

{
  autoSubfolderIndex: true,
  concurrency: 1,
  interval: 0,
  failOnError: false,
  crawlLinks: false,
  ignore: [],
  routes: [],
  retry: 3,
  retryDelay: 500
}

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

Any route (string) that starts with a prefix listed in ignore or matches a regular expression or function 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.

You can set failOnError option to true to stop the CI when Nitro could not prerender a route.

The interval and concurrency options lets you control the speed of pre-rendering, can be useful to avoid hitting some rate-limit if you call external APIs.

Set autoSubfolderIndex lets you control how to generate the files in the .output/public directory:

# autoSubfolderIndex: true (default)
/about -> .output/public/about/index.html
# autoSubfolderIndex: false
/about -> .output/public/about.html

This option is useful when your hosting provider does not give you an option regarding the trailing slash.

The prerenderer will attempt to render pages 3 times with a delay of 500ms. Use retry and retryDelay to change this behavior.

Directories

workspaceDir

Project workspace root directory.

The workspace (e.g. pnpm workspace) directory is automatically detected when the workspaceDir option is not set.

rootDir

Project main directory.

serverDir

  • Default: false
  • Type: boolean | "./" | "./server" | string

Server directory for scanning api/, routes/, plugins/, utils/, middleware/, assets/, and tasks/ folders.

When set to false, automatic directory scanning is disabled. Set to "./" to use the root directory, or "./server" to use a server/ subdirectory.

scanDirs

  • Default: (source directory when empty array)

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

apiDir

  • Default: api

Defines a different directory to scan for api route handlers.

routesDir

  • Default: routes

Defines a different directory to scan for route handlers.

buildDir

  • Default: node_modules/.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.

Build

builder

  • Type: "rollup" | "rolldown" | "vite"
  • Default: undefined (auto-detected)

Specify the bundler to use for building.

rollupConfig

Additional rollup configuration.

rolldownConfig

Additional rolldown configuration.

entry

Bundler entry point.

unenv

unenv preset(s) for environment compatibility.

alias

Path aliases for module resolution.

minify

  • Default: false

Minify bundle.

inlineDynamicImports

  • Default: false

Bundle all code into a single file instead of creating separate chunks per route.

When false, each route handler becomes a separate chunk loaded on-demand. When true, everything is bundled together. Some presets enable this by default.

sourcemap

  • Default: false

Enable source map generation. See options.

node

  • Default: true

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

moduleSideEffects

Default: ['unenv/polyfill/']

Specifies module imports that have side-effects.

replace

Build-time string replacements.

commonJS

Specifies additional configuration for the rollup CommonJS plugin.

exportConditions

Custom export conditions for module resolution.

noExternals

  • Default: false

Prevent specific packages from being externalized. Set to true to bundle all dependencies, or pass an array of package names/patterns.

traceDeps

  • Default: []

Additional dependencies to trace and include in the build output.

oxc

OXC options for rolldown builds. Includes minify and transform sub-options.

Advanced

dev

  • Default: true for development and false for production.

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

typescript

Default: { strict: true, generateRuntimeConfigTypes: false, generateTsConfig: false }

TypeScript configuration options including strict, generateRuntimeConfigTypes, generateTsConfig, tsConfig, generatedTypesDir, and tsconfigPath.

hooks

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

nitro hooks. See 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.

framework

  • Default: { name: "nitro", version: "<current>" }

Framework information. Used by presets and build info. Typically set by higher-level frameworks (e.g. Nuxt).

Preset options

firebase

The options for the firebase functions preset. See Preset Docs

vercel

The options for the vercel preset. See Preset Docs

cloudflare

The options for the cloudflare preset. See Preset Docs