@nuxt/docs 3.17.1 → 3.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,64 +8,80 @@ links:
8
8
  size: xs
9
9
  ---
10
10
 
11
- Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the `useNuxt` and `tryUseNuxt` functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as argument.
11
+ Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the `useNuxt` and `tryUseNuxt` functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as an argument.
12
12
 
13
13
  ::note
14
- When you're working with the `setup` function in Nuxt modules, Nuxt is already provided as the second argument. This means you can directly utilize it without needing to call `useNuxt()`. You can look at [Nuxt Site Config](https://github.com/harlan-zw/nuxt-site-config) as an example of usage.
14
+ When you're working with the `setup` function in Nuxt modules, Nuxt is already provided as the second argument. This means you can access it directly without needing to call `useNuxt()`.
15
15
  ::
16
16
 
17
17
  ## `useNuxt`
18
18
 
19
19
  Get the Nuxt instance from the context. It will throw an error if Nuxt is not available.
20
20
 
21
- ### Type
21
+ ### Usage
22
22
 
23
23
  ```ts
24
- function useNuxt(): Nuxt
24
+ import { useNuxt } from '@nuxt/kit'
25
+
26
+ const setupSomeFeature = () => {
27
+ const nuxt = useNuxt()
25
28
 
26
- interface Nuxt {
27
- options: NuxtOptions
28
- hooks: Hookable<NuxtHooks>
29
- hook: Nuxt['hooks']['hook']
30
- callHook: Nuxt['hooks']['callHook']
31
- addHooks: Nuxt['hooks']['addHooks']
32
- ready: () => Promise<void>
33
- close: () => Promise<void>
34
- server?: any
35
- vfs: Record<string, string>
36
- apps: Record<string, NuxtApp>
29
+ // You can now use the nuxt instance
30
+ console.log(nuxt.options)
37
31
  }
38
32
  ```
39
33
 
34
+ ### Type
35
+
36
+ ```ts twoslash
37
+ // @errors: 2391
38
+ import type { Nuxt } from '@nuxt/schema'
39
+ // ---cut---
40
+ function useNuxt(): Nuxt
41
+ ```
42
+
43
+ ### Return Value
44
+
45
+ The `useNuxt` function returns the Nuxt instance, which contains all the options and methods available in Nuxt.
46
+
47
+ | Property | Type | Description |
48
+ | ---------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
49
+ | `options` | `NuxtOptions` | The resolved Nuxt configuration. |
50
+ | `hooks` | `Hookable<NuxtHooks>` | The Nuxt hook system. Allows registering and listening to lifecycle events. |
51
+ | `hook` | `(name: string, (...args: any[]) => Promise<void> \| void) => () => void` | Shortcut for `nuxt.hooks.hook`. Registers a single callback for a specific lifecycle hook. |
52
+ | `callHook` | `(name: string, ...args: any[]) => Promise<any>` | Shortcut for `nuxt.hooks.callHook`. Triggers a lifecycle hook manually and runs all registered callbacks. |
53
+ | `addHooks` | `(configHooks: NestedHooks) => () => void` | Shortcut for `nuxt.hooks.addHooks`. Registers multiple hooks at once. |
54
+
40
55
  ### Examples
41
56
 
42
57
  ::code-group
43
58
 
44
- ```ts [setupTranspilation.ts]
45
- // https://github.com/Lexpeartha/nuxt-xstate/blob/main/src/parts/transpile.ts
59
+ ```ts twoslash [setupTranspilation.ts]
46
60
  import { useNuxt } from '@nuxt/kit'
47
61
 
48
62
  export const setupTranspilation = () => {
49
63
  const nuxt = useNuxt()
50
64
 
51
- nuxt.options.build.transpile = nuxt.options.build.transpile || []
52
-
53
65
  if (nuxt.options.builder === '@nuxt/webpack-builder') {
54
- nuxt.options.build.transpile.push(
55
- 'xstate',
56
- )
66
+ nuxt.options.build.transpile ||= []
67
+ nuxt.options.build.transpile.push('xstate')
57
68
  }
58
69
  }
59
70
  ```
60
71
 
61
- ```ts [module.ts]
62
- import { useNuxt } from '@nuxt/kit'
72
+ ```ts twoslash [module.ts]
73
+ // @module: esnext
74
+ // @filename: setupTranspilation.ts
75
+ export const setupTranspilation = () => {}
76
+ // @filename: module.ts
77
+ import { defineNuxtModule } from '@nuxt/kit'
78
+ // ---cut---
63
79
  import { setupTranspilation } from './setupTranspilation'
64
80
 
65
81
  export default defineNuxtModule({
66
- setup() {
82
+ setup () {
67
83
  setupTranspilation()
68
- }
84
+ },
69
85
  })
70
86
  ```
71
87
 
@@ -75,55 +91,83 @@ export default defineNuxtModule({
75
91
 
76
92
  Get the Nuxt instance from the context. It will return `null` if Nuxt is not available.
77
93
 
78
- ### Type
94
+ ### Usage
79
95
 
80
- ```ts
81
- function tryUseNuxt(): Nuxt | null
96
+ ```ts twoslash
97
+ import { tryUseNuxt } from '@nuxt/kit'
82
98
 
83
- interface Nuxt {
84
- options: NuxtOptions
85
- hooks: Hookable<NuxtHooks>
86
- hook: Nuxt['hooks']['hook']
87
- callHook: Nuxt['hooks']['callHook']
88
- addHooks: Nuxt['hooks']['addHooks']
89
- ready: () => Promise<void>
90
- close: () => Promise<void>
91
- server?: any
92
- vfs: Record<string, string>
93
- apps: Record<string, NuxtApp>
99
+ function setupSomething () {
100
+ const nuxt = tryUseNuxt()
101
+
102
+ if (nuxt) {
103
+ // You can now use the nuxt instance
104
+ console.log(nuxt.options)
105
+ } else {
106
+ console.log('Nuxt is not available')
107
+ }
94
108
  }
95
109
  ```
96
110
 
111
+ ### Type
112
+
113
+ ```ts twoslash
114
+ // @errors: 2391
115
+ import type { Nuxt } from '@nuxt/schema'
116
+ // ---cut---
117
+ function tryUseNuxt(): Nuxt | null
118
+ ```
119
+
120
+ ### Return Value
121
+
122
+ The `tryUseNuxt` function returns the Nuxt instance if available, or `null` if Nuxt is not available.
123
+
124
+ The Nuxt instance as described in the `useNuxt` section.
125
+
97
126
  ### Examples
98
127
 
99
128
  ::code-group
100
129
 
101
- ```ts [requireSiteConfig.ts]
102
- // https://github.com/harlan-zw/nuxt-site-config/blob/main/test/assertions.test.ts
130
+ ```ts twoslash [requireSiteConfig.ts]
131
+ declare module '@nuxt/schema' {
132
+ interface NuxtOptions {
133
+ siteConfig: SiteConfig
134
+ }
135
+ }
136
+ // ---cut---
103
137
  import { tryUseNuxt } from '@nuxt/kit'
104
138
 
105
139
  interface SiteConfig {
106
- title: string
140
+ title?: string
107
141
  }
108
142
 
109
143
  export const requireSiteConfig = (): SiteConfig => {
110
144
  const nuxt = tryUseNuxt()
111
145
  if (!nuxt) {
112
- return { title: null }
146
+ return {}
113
147
  }
114
148
  return nuxt.options.siteConfig
115
149
  }
116
150
  ```
117
151
 
118
- ```ts [module.ts]
119
- import { useNuxt } from '@nuxt/kit'
152
+ ```ts twoslash [module.ts]
153
+ // @module: esnext
154
+ // @filename: requireSiteConfig.ts
155
+ interface SiteConfig {
156
+ title?: string
157
+ }
158
+ export const requireSiteConfig = (): SiteConfig => {
159
+ return {}
160
+ }
161
+ // @filename: module.ts
162
+ // ---cut---
163
+ import { defineNuxtModule, useNuxt } from '@nuxt/kit'
120
164
  import { requireSiteConfig } from './requireSiteConfig'
121
165
 
122
166
  export default defineNuxtModule({
123
- setup(_, nuxt) {
167
+ setup (_, nuxt) {
124
168
  const config = requireSiteConfig()
125
169
  nuxt.options.app.head.title = config.title
126
- }
170
+ },
127
171
  })
128
172
  ```
129
173
 
@@ -16,258 +16,149 @@ In Nuxt, routes are automatically generated based on the structure of the files
16
16
  Watch Vue School video about extendPages.
17
17
  ::
18
18
 
19
- ### Type
20
-
21
- ```ts
22
- function extendPages (callback: (pages: NuxtPage[]) => void): void
23
-
24
- type NuxtPage = {
25
- name?: string
26
- path: string
27
- file?: string
28
- meta?: Record<string, any>
29
- alias?: string[] | string
30
- redirect?: RouteLocationRaw
31
- children?: NuxtPage[]
32
- }
33
- ```
34
-
35
- ### Parameters
36
-
37
- #### `callback`
19
+ ### Usage
38
20
 
39
- **Type**: `(pages: NuxtPage[]) => void`
40
-
41
- **Required**: `true`
42
-
43
- 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.
44
-
45
- ### Examples
46
-
47
- ```ts
48
- // https://github.com/nuxt-modules/prismic/blob/master/src/module.ts
21
+ ```ts twoslash
49
22
  import { createResolver, defineNuxtModule, extendPages } from '@nuxt/kit'
50
23
 
51
24
  export default defineNuxtModule({
52
- setup(options) {
53
- const resolver = createResolver(import.meta.url)
25
+ setup (options) {
26
+ const { resolve } = createResolver(import.meta.url)
54
27
 
55
28
  extendPages((pages) => {
56
29
  pages.unshift({
57
30
  name: 'prismic-preview',
58
31
  path: '/preview',
59
- file: resolver.resolve('runtime/preview.vue')
60
- })
32
+ file: resolve('runtime/preview.vue'),
33
+ })
61
34
  })
62
- }
35
+ },
63
36
  })
64
37
  ```
65
38
 
66
- ## `extendRouteRules`
67
-
68
- 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.
69
-
70
- ::tip
71
- You can read more about Nitro route rules in the [Nitro documentation](https://nitro.unjs.io/guide/routing#route-rules).
72
- ::
73
-
74
- ::tip{icon="i-lucide-video" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
75
- Watch Vue School video about adding route rules and route middelwares.
76
- ::
77
-
78
39
  ### Type
79
40
 
80
41
  ```ts
81
- function extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions): void
82
-
83
- interface NitroRouteConfig {
84
- cache?: CacheOptions | false;
85
- headers?: Record<string, string>;
86
- redirect?: string | { to: string; statusCode?: HTTPStatusCode };
87
- prerender?: boolean;
88
- proxy?: string | ({ to: string } & ProxyOptions);
89
- isr?: number | boolean;
90
- cors?: boolean;
91
- swr?: boolean | number;
92
- static?: boolean | number;
93
- }
94
-
95
- interface ExtendRouteRulesOptions {
96
- override?: boolean
97
- }
98
-
99
- interface CacheOptions {
100
- swr?: boolean
101
- name?: string
102
- group?: string
103
- integrity?: any
104
- maxAge?: number
105
- staleMaxAge?: number
106
- base?: string
107
- headersOnly?: boolean
108
- }
109
-
110
- // See https://www.jsdocs.io/package/h3#ProxyOptions
111
- interface ProxyOptions {
112
- headers?: RequestHeaders | HeadersInit;
113
- fetchOptions?: RequestInit & { duplex?: Duplex } & {
114
- ignoreResponseError?: boolean;
115
- };
116
- fetch?: typeof fetch;
117
- sendStream?: boolean;
118
- streamRequest?: boolean;
119
- cookieDomainRewrite?: string | Record<string, string>;
120
- cookiePathRewrite?: string | Record<string, string>;
121
- onResponse?: (event: H3Event, response: Response) => void;
122
- }
42
+ function extendPages(callback: (pages: NuxtPage[]) => void): void
123
43
  ```
124
44
 
125
45
  ### Parameters
126
46
 
127
- #### `route`
128
-
129
- **Type**: `string`
47
+ **callback**: 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.
130
48
 
131
- **Required**: `true`
49
+ | Property | Type | Required | Description |
50
+ | ---------- | ---------------------------------- | -------- | -------------------------------------------------------------------------------------------- |
51
+ | `name` | `string` | `false` | The name of the route. Useful for programmatic navigation and identifying routes. |
52
+ | `path` | `string` | `false` | The route URL path. If not set, Nuxt will infer it from the file location. |
53
+ | `file` | `string` | `false` | Path to the Vue file that should be used as the component for the route. |
54
+ | `meta` | `Record<string, any>`{lang="ts"} | `false` | Custom metadata for the route. Can be used in layouts, middlewares, or navigation guards. |
55
+ | `alias` | `string[] \| string`{lang="ts"} | `false` | One or more alias paths for the route. Useful for supporting multiple URLs. |
56
+ | `redirect` | `RouteLocationRaw`{lang="ts"} | `false` | Redirect rule for the route. Supports named routes, objects, or string paths. |
57
+ | `children` | `NuxtPage[]`{lang="ts"} | `false` | Nested child routes under this route for layout or view nesting. |
132
58
 
133
- A route pattern to match against.
134
-
135
- #### `rule`
136
-
137
- **Type**: `NitroRouteConfig`
138
-
139
- **Required**: `true`
140
-
141
- A route configuration to apply to the matched route.
59
+ ## `extendRouteRules`
142
60
 
143
- #### `options`
61
+ 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.
144
62
 
145
- **Type**: `ExtendRouteRulesOptions`
63
+ ::tip
64
+ You can read more about Nitro route rules in the [Nitro documentation](https://nitro.unjs.io/guide/routing#route-rules).
65
+ ::
146
66
 
147
- **Default**: `{}`
67
+ ::tip{icon="i-lucide-video" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
68
+ Watch Vue School video about adding route rules and route middelwares.
69
+ ::
148
70
 
149
- Options to pass to the route configuration. If `override` is set to `true`, it will override the existing route configuration.
71
+ ### Usage
150
72
 
151
- ### Examples
152
-
153
- ```ts
154
- // https://github.com/directus/website/blob/main/modules/redirects.ts
155
- import { createResolver, defineNuxtModule, extendRouteRules, extendPages } from '@nuxt/kit'
73
+ ```ts twoslash
74
+ import { createResolver, defineNuxtModule, extendPages, extendRouteRules } from '@nuxt/kit'
156
75
 
157
76
  export default defineNuxtModule({
158
- setup(options) {
159
- const resolver = createResolver(import.meta.url)
77
+ setup (options) {
78
+ const { resolve } = createResolver(import.meta.url)
160
79
 
161
80
  extendPages((pages) => {
162
81
  pages.unshift({
163
82
  name: 'preview-new',
164
83
  path: '/preview-new',
165
- file: resolver.resolve('runtime/preview.vue')
166
- })
84
+ file: resolve('runtime/preview.vue'),
85
+ })
167
86
  })
168
87
 
169
88
  extendRouteRules('/preview', {
170
89
  redirect: {
171
90
  to: '/preview-new',
172
- statusCode: 302
173
- }
91
+ statusCode: 302,
92
+ },
174
93
  })
175
94
 
176
95
  extendRouteRules('/preview-new', {
177
96
  cache: {
178
- maxAge: 60 * 60 * 24 * 7
179
- }
97
+ maxAge: 60 * 60 * 24 * 7,
98
+ },
180
99
  })
181
- }
100
+ },
182
101
  })
183
102
  ```
184
103
 
185
- ## `addRouteMiddleware`
186
-
187
- Registers route middlewares to be available for all routes or for specific routes.
188
-
189
- Route middlewares can be also defined in plugins via [`addRouteMiddleware`](/docs/api/utils/add-route-middleware) composable.
190
-
191
- ::tip
192
- Read more about route middlewares in the [Route middleware documentation](/docs/getting-started/routing#route-middleware).
193
- ::
194
-
195
- ::tip{icon="i-lucide-video" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
196
- Watch Vue School video about adding route rules and route middelwares.
197
- ::
198
-
199
104
  ### Type
200
105
 
201
106
  ```ts
202
- function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions): void
203
-
204
- type NuxtMiddleware = {
205
- name: string
206
- path: string
207
- global?: boolean
208
- }
209
-
210
- interface AddRouteMiddlewareOptions {
211
- override?: boolean
212
- prepend?: boolean
213
- }
107
+ function extendRouteRules(route: string, rule: NitroRouteConfig, options?: ExtendRouteRulesOptions): void
214
108
  ```
215
109
 
216
110
  ### Parameters
217
111
 
218
- #### `input`
219
-
220
- **Type**: `NuxtMiddleware | NuxtMiddleware[]`
221
-
222
- **Required**: `true`
223
-
224
- A middleware object or an array of middleware objects with the following properties:
225
-
226
- - `name` (required)
227
-
228
- **Type**: `string`
229
-
230
- Middleware name.
231
-
232
- - `path` (required)
233
-
234
- **Type**: `string`
235
-
236
- Path to the middleware.
112
+ **route**: A route pattern to match against.\
113
+ **rule**: A route rule configuration to apply to the matched route.
237
114
 
238
- - `global` (optional)
239
-
240
- **Type**: `boolean`
241
-
242
- If enabled, registers middleware to be available for all routes.
243
-
244
- #### `options`
115
+ ::tip
116
+ About route rules configurations, you can get more detail in [Hybrid Rendering > Route Rules](/docs/guide/concepts/rendering#route-rules).
117
+ ::
245
118
 
246
- **Type**: `AddRouteMiddlewareOptions`
119
+ **options**: A object to pass to the route configuration. If `override` is set to `true`, it will override the existing route configuration.
247
120
 
248
- **Default**: `{}`
121
+ | Name | Type | Default | Description |
122
+ | ---------- | --------- | ------- | -------------------------------------------- |
123
+ | `override` | `boolean` | `false` | Override route rule config, default is false |
249
124
 
250
- - `override` (optional)
125
+ ## `addRouteMiddleware`
251
126
 
252
- **Type**: `boolean`
127
+ Registers route middlewares to be available for all routes or for specific routes.
253
128
 
254
- **Default**: `false`
129
+ Route middlewares can be also defined in plugins via [`addRouteMiddleware`](/docs/api/utils/add-route-middleware) composable.
255
130
 
256
- If enabled, overrides the existing middleware with the same name.
131
+ ::tip
132
+ Read more about route middlewares in the [Route middleware documentation](/docs/getting-started/routing#route-middleware).
133
+ ::
257
134
 
258
- - `prepend` (optional)
135
+ ::tip{icon="i-lucide-video" to="https://vueschool.io/lessons/adding-route-rules-and-route-middlewares?friend=nuxt" target="_blank"}
136
+ Watch Vue School video about adding route rules and route middelwares.
137
+ ::
259
138
 
260
- **Type**: `boolean`
139
+ ### Usage
261
140
 
262
- **Default**: `false`
141
+ ::code-group
263
142
 
264
- If enabled, prepends the middleware to the list of existing middleware.
143
+ ```ts twoslash [module.ts]
144
+ import { addRouteMiddleware, createResolver, defineNuxtModule } from '@nuxt/kit'
265
145
 
266
- ### Examples
146
+ export default defineNuxtModule({
147
+ setup () {
148
+ const { resolve } = createResolver(import.meta.url)
267
149
 
268
- ::code-group
150
+ addRouteMiddleware({
151
+ name: 'auth',
152
+ path: resolve('runtime/auth.ts'),
153
+ global: true,
154
+ }, { prepend: true })
155
+ },
156
+ })
157
+ ```
269
158
 
270
- ```ts [runtime/auth.ts]
159
+ ```ts twoslash [runtime/auth.ts]
160
+ function isAuthenticated(): boolean { return false }
161
+ // ---cut---
271
162
  export default defineNuxtRouteMiddleware((to, from) => {
272
163
  // isAuthenticated() is an example method verifying if a user is authenticated
273
164
  if (to.path !== '/login' && isAuthenticated() === false) {
@@ -276,20 +167,27 @@ export default defineNuxtRouteMiddleware((to, from) => {
276
167
  })
277
168
  ```
278
169
 
279
- ```ts [module.ts]
280
- import { createResolver, defineNuxtModule, addRouteMiddleware } from '@nuxt/kit'
170
+ ::
281
171
 
282
- export default defineNuxtModule({
283
- setup() {
284
- const resolver = createResolver(import.meta.url)
172
+ ### Type
285
173
 
286
- addRouteMiddleware({
287
- name: 'auth',
288
- path: resolver.resolve('runtime/auth.ts'),
289
- global: true
290
- }, { prepend: true })
291
- }
292
- })
174
+ ```ts
175
+ function addRouteMiddleware(input: NuxtMiddleware | NuxtMiddleware[], options?: AddRouteMiddlewareOptions): void
293
176
  ```
294
177
 
295
- ::
178
+ ### Parameters
179
+
180
+ **input**: A middleware object or an array of middleware objects with the following properties:
181
+
182
+ | Property | Type | Required | Description |
183
+ | -------- | --------- | -------- | --------------------------------------------------- |
184
+ | `name` | `string` | `true` | The name of the middleware. |
185
+ | `path` | `string` | `true` | The file path to the middleware. |
186
+ | `global` | `boolean` | `false` | If set to `true`, applies middleware to all routes. |
187
+
188
+ **options**: An object with the following properties:
189
+
190
+ | Property | Type | Default | Description |
191
+ | ---------- | --------- | ------- | ----------------------------------------------------------- |
192
+ | `override` | `boolean` | `false` | If `true`, replaces middleware with the same name. |
193
+ | `prepend` | `boolean` | `false` | If `true`, prepends middleware before existing middlewares. |