Skip to content

Commit

Permalink
docs(routing): add route rules
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux authored Apr 18, 2023
1 parent ff3964e commit 46740e6
Showing 1 changed file with 55 additions and 4 deletions.
59 changes: 55 additions & 4 deletions docs/content/1.guide/3.routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ title: Routing
icon: ri:direction-line
---

# Filesystem Routing
# Routing

Nitro support filesystem routing as well as defining route rules for maximum flexibility and performance.

## Filesystem Routing

Nitro supports file-based routing for your API routes.

Expand All @@ -13,8 +17,6 @@ Handler files inside `api/` and `routes/` directory will be automatically mapped
Due to some providers like Vercel using top-level `api/` directory as a feature, Nitro also supports `routes/api/` to create API routes.
::

## Usage

```md
api/
test.ts <-- /api/test
Expand All @@ -23,8 +25,9 @@ routes/
nitro.config.ts
```

::alert
If you are using [Nuxt](https://nuxt.com), move the `api/` and `routes/` inside the `server/` directory.

::

### Simple route

Expand Down Expand Up @@ -96,3 +99,51 @@ Check out [h3 JSDocs](https://www.jsdocs.io/package/h3#package-index-functions)
export default eventHandler(event => `Default page`)
```

## Route Rules

Nitro allows you to add logic at the top-level of your configuration, useful for redirecting, proxying, caching and adding headers to routes.

It is a map from route pattern (following [unjs/radix3](https://github.com/unjs/radix3#route-matcher)) to route options.

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

See the [Cache API](/guide/cache) for all available cache options.

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

**Example:**

::code-group
```ts [nitro.config.ts]
export default defineNitroConfig({
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' },
'/proxy/example': { proxy: 'https://example.com' },
'/proxy/**': { proxy: '/api/**' },
}
})
```
```ts [nuxt.config.ts]
export default defineNuxtConfig({
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' },
'/proxy/example': { proxy: 'https://example.com' },
'/proxy/**': { proxy: '/api/**' },
}
})
```
::

0 comments on commit 46740e6

Please sign in to comment.