路由

用于定义路由、处理器和路由级行为的选项。

Note

本页所有示例都假设已在 nitro.config.ts 中导入以下内容:

import { defineConfig } from "nitro";

#baseURL

  • 默认值:"/"(也可通过 NITRO_APP_BASE_URL 环境变量设置)

服务器的主基础 URL。

export default defineConfig({
  baseURL: "/app/", // serve app under /app/ prefix
});

使用 Vite 插件时,Vite 的 base 路径默认为 baseURL,而 baseURL 默认为 Vite 的 base。设置 baseURL: "/" 可让服务器继续从根路径提供服务(例如代理会移除基础路径时)。

Note

在早期 config 钩子中读取 Vite base 的框架(例如 TanStack Start)无法获取通过 baseURL 设置的值。对这类框架,请直接设置 Vite base。

使用 Rsbuild 插件时,baseURL 会设置 Rsbuild 的 server.base;只设置 server.base 时,它会作为默认的 baseURL。

#apiBaseURL

  • 默认值:"/api"

更改默认的 API 基础 URL 前缀。

export default defineConfig({
  apiBaseURL: "/server/api", // api routes under /server/api/
});

#serverEntry

  • 类型:false | string | { handler: string, format?: EventHandlerFormat }

自定义服务器入口配置。设为 false 可禁用默认服务器入口。

export default defineConfig({
  serverEntry: "./server.ts",
});
Read more in Docs > Server Entry.

#handlers

服务器处理器和路由。

如果服务器目录中存在 routes/、api/ 或 middleware/ 目录,这些目录会自动添加到处理器数组中。

export default defineConfig({
  handlers: [
    { route: "/health", handler: "./handlers/health.ts" },
    { route: "/admin/**", handler: "./handlers/admin.ts", method: "get" },
  ],
});
Read more in Docs > Routing.

#devHandlers

以程序实例而非文件路径提供的处理器。常规 handlers 会由打包器导入和转换,而 devHandlers 可以直接接收处理器函数。

注意: 这些处理器仅在开发模式下可用,不会包含在生产构建中。

export default defineConfig({
  devHandlers: [
    { route: "/__dev", handler: defineHandler(() => "dev-only route") },
  ],
});

#routes

  • 默认值:{}

内联路由定义。路由模式到处理器路径或处理器选项的映射。

export default defineConfig({
  routes: {
    "/hello": "./routes/hello.ts",
    "/greet": { handler: "./routes/greet.ts", method: "post" },
  },
});

#errorHandler

  • 类型:string | string[]

自定义运行时错误处理器的路径。设置后会替换 Nitro 内置的错误页。

import { defineConfig } from "nitro";

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

#routeRules

🧪 实验性功能

路由选项。该映射将路由模式(遵循 rou3)对应到路由选项。

设置 cache 选项时,匹配该模式的处理器会自动由 defineCachedHandler 包装。

所有可用的缓存选项请参见缓存 API。

Note

swr: true|number 是 cache: { swr: true, maxAge: number } 的简写。

routeRules: {
  '/blog/**': { swr: true },
  '/feed/**': { swr: 600 },
  '/docs/**': { static: true },
  '/dashboard/**': { 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/**' },
}
Read more in Docs > Routing#route Rules.

#prerender

预渲染选项。构建期间会请求指定的路由,并将其作为静态资源复制到 .output/public 目录。

默认值:

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

以 ignore 中某个前缀开头,或匹配路由模式(包含 * 或 : 的字符串,例如 /blog/** 或 /users/:id)、正则表达式或函数的路由都会被忽略。详情请参阅预渲染。

将 crawlLinks 设为 true 后,Nitro 默认从 / 开始(或从 routes 数组中的所有路由开始),提取 HTML 页面中的 <a> 标签,并对这些链接也进行预渲染。

可以将 failOnError 设为 true,在 Nitro 无法预渲染某个路由时中止 CI。将状态码列入 ignoreStatusCodes(例如 [404]),可避免这些状态码导致的路由失败中止构建;如果所有预渲染路由都失败且没有写入任何内容,构建仍会中止。

interval 和 concurrency 选项可以控制预渲染速度,在调用外部 API 时有助于避免触发速率限制。

autoSubfolderIndex 选项控制如何在 .output/public 目录中生成文件:

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

当托管平台不提供尾部斜杠相关选项时,此选项会很有用。

将 ignoreUnprefixedPublicAssets 设为 true 可跳过未带基础 URL 前缀的公共资源预渲染。