网页 综合 更新时间 2026-11-13 17:03:40

Routing - Nitro

自动蜘蛛 nitro.build 正文约 5777 字
Routing - Nitro
Nitro supports filesystem routing to automatically map files to routes. Routes are compiled and code-split at build time, removing the need for a runtime router.
A route handler is a function that receives an event object (H3Event) and returns a response.
Files are automatically mapped to h3 routes. Defining a route is as simple as creating a file inside the api/ or routes/ directory of your serverDir.
Filesystem routing requires setting serverDir (or scanDirs) in your config; no directories are scanned by default.
Each file defines a single handler, and you can append the HTTP method to the filename to match a specific request method.
You can nest routes by creating subdirectories.
To organize related route files without affecting the resulting URLs, put them in a folder wrapped in parentheses ( and ).
Route groups are not part of the route path and are only used for organization purposes.
Create a file in the routes/ or routes/api/ directory. The file path becomes the route path. Then export a route handler:
Apart from [param], [...param] and (group)/, characters in file names are matched literally: routes/example:action.ts handles only /example:action, and routes/v(1)+.ts handles only /v(1)+. Windows does not allow :, * or ? in file names; register such routes with the routes config instead.
To define a route with params, use the [<param>] syntax where <param> is the name of the param. The param will be available on the event.context.params object.
Calling /hello/nitro returns:
You can define multiple params in a route using [<param1>]/[<param2>] syntax where each param is a folder. You cannot define multiple params in a single filename or folder.
You can capture all the remaining parts of a URL using [...<param>] syntax. This will include the / in the param.
Calling /hello/nitro/is/hot returns:
A catch-all param also matches the base path: /hello and /hello/ are handled by routes/hello/[...name].ts too, with name being undefined (for /hello) or "" (for /hello/). A sibling routes/hello/index.ts takes precedence for the base path. A root routes/[...name].ts also matches /, with name being "".
When catch-alls are nested, the innermost one handles its own base path. With routes/[...slug].ts and routes/docs/[...path].ts, /docs is handled by docs/[...path].ts (with path undefined), not by the root catch-all.
You can append the HTTP method to the filename to force the route to be matched only for a specific HTTP request method, for example hello.get.ts will only match for GET requests. You can use any HTTP method you want.
Supported methods: get, post, put, delete, patch, head, options, query, connect, trace.
A .get route also handles HEAD requests (and GET-scoped middleware runs for them too), unless a .head route exists with the same route pattern. Like any other route, the most specific match wins, so users/[id].get.ts handles HEAD /users/1 over users/[...].head.ts. The response body is always dropped for HEAD requests, including those handled by a .head route.
To keep a GET handler from running for HEAD requests, for example when it has side effects or opens a stream, register it with head: false in the routes or handlers config, or add a .head route with the same route pattern (filesystem routes can only use the latter). HEAD requests then fall through to other matching routes, or get a 405 Method Not Allowed response.
query matches the QUERY method, a safe and idempotent alternative to GET that carries a request body. Support across proxies, CDNs and deployment platforms is still uneven, so keep a GET or POST fallback for public APIs.
Use the .ws suffix (for example, chat.ws.ts) for a route that only handles WebSocket upgrade requests.
When a request path matches a route only for other methods, Nitro responds with 405 Method Not Allowed and an Allow header listing them. If a catch-all route (such as routes/[...].ts, a renderer or a server entry) matches the request, it handles it instead.
You can create a special route that matches all requests not handled by any other route, useful as a default or fallback route.
To create a catch-all route, create a file named [...].ts.
With an unnamed catch-all ([...].ts), the matched wildcard segments are available as event.context.params[0].
The server entry and renderer also act as catch-all handlers and are chained after file-based catch-all routes.
You can include a route only in specific builds by adding a .dev, .prod, or .prerender suffix to the filename, for example: routes/test.get.dev.ts or routes/test.get.prod.ts.
The suffix is placed after the method suffix (if any):
To target multiple environments, or a preset name as the environment, register the route programmatically via the routes config.
Nitro reserves trailing lowercase suffixes in the names of scanned files (routes/, api/, middleware/, plugins/, tasks/ and modules/) for its own conventions. Known file extensions are kept as part of the route path:
Suffixes with digits, uppercase letters or other characters (e.g. v1.2.ts) are always kept, and so is the name after a numeric order prefix (e.g. middleware/1.logger.ts).
To keep a custom suffix, add it to the scanSuffixes config:
Test files (*.test.ts, *.spec.ts) and type declarations (*.d.ts) are never registered, so they can live next to your handlers.
You can use the ignore config option to exclude files from route scanning. It accepts an array of glob patterns relative to the server directory.
You can define route metadata at build time using the defineRouteMeta macro in your route handler files.
This feature is currently experimental.
In addition to filesystem routing, you can register route handlers programmatically using the routes config option.
The routes option allows you to map route patterns to handlers:
访问原文 返回搜索 https://nitro.build/docs/routing
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。