Nuxt/docs/3.api/5.kit/7.pages.md

296 lines
7.2 KiB
Markdown

---
title: Pages
description: Nuxt Kit provides a set of utilities to help you create and use pages. You can use these utilities to manipulate the pages configuration or to define route rules.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/kit/src/pages.ts
size: xs
---
## `extendPages`
In Nuxt 3, routes are automatically generated based on the structure of the files in the `pages` directory. However, there may be scenarios where you'd want to customize these routes. For instance, you might need to add a route for a dynamic page not generated by Nuxt, remove an existing route, or modify the configuration of a route. For such customizations, Nuxt offers the `extendPages` feature, which allows you to extend and alter the pages configuration.
::tip{icon="i-ph-video-duotone" to="https://vueschool.io/lessons/extend-and-alter-nuxt-pages?friend=nuxt" target="_blank"}
Watch Vue School video about extendPages.
::
### Type
```ts
function extendPages (callback: (pages: NuxtPage[]) => void): void
type NuxtPage = {
name?: string
path: string
file?: string
meta?: Record<string, any>
alias?: string[] | string
redirect?: RouteLocationRaw
children?: NuxtPage[]
}
```
### Parameters
#### `callback`
**Type**: `(pages: NuxtPage[]) => void`
**Required**: `true`
A function that will be called with the pages configuration. You can alter this array by adding, deleting, or modifying its elements. Note: You should modify the provided pages array directly, as changes made to a copied array will not be reflected in the configuration.
### Examples
```ts
// https://github.com/nuxt-modules/prismic/blob/master/src/module.ts
import { createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'
export default defineNuxtModule({
setup(options) {
const resolver = createResolver(import.meta.url)
extendPages((pages) => {
pages.unshift({
name: 'prismic-preview',
path: '/preview',
file: resolver.resolve('runtime/preview.vue')
})
})
}
})
```
## `extendRouteRules`
Nuxt is powered by the [Nitro](https://nitro.unjs.io) server engine. With Nitro, you can incorporate high-level logic directly into your configuration, which is useful for actions like redirects, proxying, caching, and appending headers to routes. This configuration works by associating route patterns with specific route settings.
::tip
You can read more about Nitro route rules in the [Nitro documentation](https://nitro.unjs.io/guide/routing#route-rules).
::
::tip{icon="i-ph-video-duotone" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
Watch Vue School video about adding route rules and route middelwares.
::
### Type
```ts
function extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions): void
interface NitroRouteConfig {
cache?: CacheOptions | false;
headers?: Record<string, string>;
redirect?: string | { to: string; statusCode?: HTTPStatusCode };
prerender?: boolean;
proxy?: string | ({ to: string } & ProxyOptions);
isr?: number | boolean;
cors?: boolean;
swr?: boolean | number;
static?: boolean | number;
}
interface ExtendRouteRulesOptions {
override?: boolean
}
interface CacheOptions {
swr?: boolean
name?: string
group?: string
integrity?: any
maxAge?: number
staleMaxAge?: number
base?: string
headersOnly?: boolean
}
// See https://www.jsdocs.io/package/h3#ProxyOptions
interface ProxyOptions {
headers?: RequestHeaders | HeadersInit;
fetchOptions?: RequestInit & { duplex?: Duplex } & {
ignoreResponseError?: boolean;
};
fetch?: typeof fetch;
sendStream?: boolean;
streamRequest?: boolean;
cookieDomainRewrite?: string | Record<string, string>;
cookiePathRewrite?: string | Record<string, string>;
onResponse?: (event: H3Event, response: Response) => void;
}
```
### Parameters
#### `route`
**Type**: `string`
**Required**: `true`
A route pattern to match against.
#### `rule`
**Type**: `NitroRouteConfig`
**Required**: `true`
A route configuration to apply to the matched route.
#### `options`
**Type**: `ExtendRouteRulesOptions`
**Default**: `{}`
Options to pass to the route configuration. If `override` is set to `true`, it will override the existing route configuration.
### Examples
```ts
// https://github.com/directus/website/blob/main/modules/redirects.ts
import { createResolver, defineNuxtModule, extendRouteRules, extendPages } from '@nuxt/kit'
export default defineNuxtModule({
setup(options) {
const resolver = createResolver(import.meta.url)
extendPages((pages) => {
pages.unshift({
name: 'preview-new',
path: '/preview-new',
file: resolver.resolve('runtime/preview.vue')
})
})
extendRouteRules('/preview', {
redirect: {
to: '/preview-new',
statusCode: 302
}
})
extendRouteRules('/preview-new', {
cache: {
maxAge: 60 * 60 * 24 * 7
}
})
}
})
```
## `addRouteMiddleware`
Registers route middlewares to be available for all routes or for specific routes.
Route middlewares can be also defined in plugins via [`addRouteMiddleware`](/docs/api/utils/add-route-middleware) composable.
::tip
Read more about route middlewares in the [Route middleware documentation](/docs/getting-started/routing#route-middleware).
::
::tip{icon="i-ph-video-duotone" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
Watch Vue School video about adding route rules and route middelwares.
::
### Type
```ts
function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions): void
type NuxtMiddleware = {
name: string
path: string
global?: boolean
}
interface AddRouteMiddlewareOptions {
override?: boolean
prepend?: boolean
}
```
### Parameters
#### `input`
**Type**: `NuxtMiddleware | NuxtMiddleware[]`
**Required**: `true`
A middleware object or an array of middleware objects with the following properties:
- `name` (required)
**Type**: `string`
Middleware name.
- `path` (required)
**Type**: `string`
Path to the middleware.
- `global` (optional)
**Type**: `boolean`
If enabled, registers middleware to be available for all routes.
#### `options`
**Type**: `AddRouteMiddlewareOptions`
**Default**: `{}`
- `override` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, overrides the existing middleware with the same name.
- `prepend` (optional)
**Type**: `boolean`
**Default**: `false`
If enabled, prepends the middleware to the list of existing middleware.
### Examples
::code-group
```ts [runtime/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
// isAuthenticated() is an example method verifying if a user is authenticated
if (to.path !== '/login' && isAuthenticated() === false) {
return navigateTo('/login')
}
})
```
```ts [module.ts]
import { createResolver, defineNuxtModule, addRouteMiddleware } from '@nuxt/kit'
export default defineNuxtModule({
setup() {
const resolver = createResolver(import.meta.url)
addRouteMiddleware({
name: 'auth',
path: resolver.resolve('runtime/auth.ts'),
global: true
}, { prepend: true })
}
})
```
::