@nuxt/docs 3.17.5 → 3.17.7

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.
@@ -230,7 +230,7 @@ Read more about `useAsyncData`.
230
230
 
231
231
  - `data`: the result of the asynchronous function that is passed in.
232
232
  - `refresh`/`execute`: a function that can be used to refresh the data returned by the `handler` function.
233
- - `clear`: a function that can be used to set `data` to `undefined`, set `error` to `null`, set `status` to `idle`, and mark any currently pending requests as cancelled.
233
+ - `clear`: a function that can be used to set `data` to `undefined` (or the value of `options.default()` if provided), set `error` to `null`, set `status` to `idle`, and mark any currently pending requests as cancelled.
234
234
  - `error`: an error object if the data fetching failed.
235
235
  - `status`: a string indicating the status of the data request (`"idle"`, `"pending"`, `"success"`, `"error"`).
236
236
 
@@ -18,7 +18,7 @@ Using Nitro gives Nuxt superpowers:
18
18
  - Universal deployment on any provider (many zero-config)
19
19
  - Hybrid rendering
20
20
 
21
- Nitro is internally using [h3](https://github.com/unjs/h3), a minimal H(TTP) framework built for high performance and portability.
21
+ Nitro is internally using [h3](https://github.com/h3js/h3), a minimal H(TTP) framework built for high performance and portability.
22
22
 
23
23
  :video-accordion{title="Watch a video from Alexander Lichter to understand the responsibilities of Nuxt and Nitro in your application" videoId="DkvgJa-X31k"}
24
24
 
@@ -135,7 +135,7 @@ export default defineNuxtConfig({
135
135
  });
136
136
  ```
137
137
 
138
- ## Runtime prerender configuration
138
+ ## Runtime Prerender Configuration
139
139
 
140
140
  ### `prerenderRoutes`
141
141
 
@@ -299,6 +299,64 @@ export default defineNuxtConfig({
299
299
  })
300
300
  ```
301
301
 
302
+ ### Corrected Module Loading Order in Layers
303
+
304
+ 🚦 **Impact Level**: Minimal
305
+
306
+ #### What Changed
307
+
308
+ The order in which modules are loaded when using [Nuxt layers](/docs/guide/going-further/layers) has been corrected. Previously, modules from the project root were loaded before modules from extended layers, which was the reverse of the expected behavior.
309
+
310
+ Now modules are loaded in the correct order:
311
+
312
+ 1. **Layer modules first** (in extend order - deeper layers first)
313
+ 2. **Project modules last** (highest priority)
314
+
315
+ This affects both:
316
+ * Modules defined in the `modules` array in `nuxt.config.ts`
317
+ * Auto-discovered modules from the `modules/` directory
318
+
319
+ #### Reasons for Change
320
+
321
+ This change ensures that:
322
+ * Extended layers have lower priority than the consuming project
323
+ * Module execution order matches the intuitive layer inheritance pattern
324
+ * Module configuration and hooks work as expected in multi-layer setups
325
+
326
+ #### Migration Steps
327
+
328
+ **Most projects will not need changes**, as this corrects the loading order to match expected behavior.
329
+
330
+ However, if your project was relying on the previous incorrect order, you may need to:
331
+
332
+ 1. **Review module dependencies**: Check if any modules depend on specific loading order
333
+ 2. **Adjust module configuration**: If modules were configured to work around the incorrect order
334
+ 3. **Test thoroughly**: Ensure all functionality works as expected with the corrected order
335
+
336
+ Example of the new correct order:
337
+ ```ts
338
+ // Layer: my-layer/nuxt.config.ts
339
+ export default defineNuxtConfig({
340
+ modules: ['layer-module-1', 'layer-module-2']
341
+ })
342
+
343
+ // Project: nuxt.config.ts
344
+ export default defineNuxtConfig({
345
+ extends: ['./my-layer'],
346
+ modules: ['project-module-1', 'project-module-2']
347
+ })
348
+
349
+ // Loading order (corrected):
350
+ // 1. layer-module-1
351
+ // 2. layer-module-2
352
+ // 3. project-module-1 (can override layer modules)
353
+ // 4. project-module-2 (can override layer modules)
354
+ ```
355
+
356
+ If you encounter issues with module order dependencies due to needing to register a hook, consider using the [`modules:done` hook](/docs/guide/going-further/modules#custom-hooks) for modules that need to call a hook. This is run after all other modules have been loaded, which means it is safe to use.
357
+
358
+ 👉 See [PR #31507](https://github.com/nuxt/nuxt/pull/31507) and [issue #25719](https://github.com/nuxt/nuxt/issues/25719) for more details.
359
+
302
360
  ### Deduplication of Route Metadata
303
361
 
304
362
  🚦 **Impact Level**: Minimal
@@ -777,7 +835,7 @@ This change should generally improve the expected behavior, but if you were expe
777
835
  query: { id },
778
836
  immediate: false
779
837
  )
780
- + watch(id, execute, { once: true })
838
+ + watch(id, () => execute(), { once: true })
781
839
  ```
782
840
 
783
841
  To opt out of this behavior:
@@ -76,17 +76,27 @@ Any redirection on the server will result in a `Location:` header being sent to
76
76
 
77
77
  :read-more{to="/docs/guide/directory-structure/middleware"}
78
78
 
79
- ### Step 6: Setup Page and Components
79
+ ### Step 6: Render Page and Components
80
80
 
81
- Nuxt initializes the page and its components during this step and fetches any required data with `useFetch` and `useAsyncData`. Since there are no dynamic updates and no DOM operations occur on the server, Vue lifecycle hooks such as `onBeforeMount`, `onMounted`, and subsequent hooks are **NOT** executed during SSR.
81
+ Nuxt renders the page and its components and fetches any required data with `useFetch` and `useAsyncData` during this step. Since there are no dynamic updates and no DOM operations occur on the server, Vue lifecycle hooks such as `onBeforeMount`, `onMounted`, and subsequent hooks are **NOT** executed during SSR.
82
+
83
+ By default, Vue pauses dependency tracking during SSR for better performance.
84
+
85
+ ::callout{icon="i-lucide-lightbulb"}
86
+ There is no reactivity on the server side because Vue SSR renders the app top-down as static HTML, making it impossible to go back and modify content that has already been rendered.
87
+ ::
82
88
 
83
89
  ::important
84
90
  You should avoid code that produces side effects that need cleanup in root scope of `<script setup>`. An example of such side effects is setting up timers with `setInterval`. In client-side only code we may setup a timer and then tear it down in `onBeforeUnmount` or `onUnmounted`. However, because the unmount hooks will never be called during SSR, the timers will stay around forever. To avoid this, move your side-effect code into `onMounted` instead.
85
91
  ::
86
92
 
87
- ### Step 7: Render and Generate HTML Output
93
+ ::tip{icon="i-lucide-video" to="https://youtu.be/dZSNW07sO-A" target="_blank"}
94
+ Watch a video from Daniel Roe explaining Server Rendering and Global State.
95
+ ::
96
+
97
+ ### Step 7: Generate HTML Output
88
98
 
89
- After all components are initialized and data is fetched, Nuxt combines the components with settings from `unhead` to generate a complete HTML document. This HTML, along with the associated data, is sent back to the client to complete the SSR process.
99
+ After all required data is fetched and the components are rendered, Nuxt combines the rendered components with settings from `unhead` to generate a complete HTML document. This HTML, along with the associated data, is then sent back to the client to complete the SSR process.
90
100
 
91
101
  ::callout{icon="i-lucide-lightbulb"}
92
102
  After rendering the Vue application to HTML, Nuxt calls the [`app:rendered`](/docs/api/advanced/hooks#app-hooks-runtime) hook.
@@ -16,7 +16,7 @@ It is shipped with many features:
16
16
 
17
17
  ## API Layer
18
18
 
19
- Server [API endpoints](/docs/guide/directory-structure/server#api-routes) and [Middleware](/docs/guide/directory-structure/server#server-middleware) are added by Nitro that internally uses [h3](https://github.com/unjs/h3).
19
+ Server [API endpoints](/docs/guide/directory-structure/server#api-routes) and [Middleware](/docs/guide/directory-structure/server#server-middleware) are added by Nitro that internally uses [h3](https://github.com/h3js/h3).
20
20
 
21
21
  Key features include:
22
22
 
@@ -24,7 +24,7 @@ Key features include:
24
24
  - Handlers can return promises, which will be awaited (`res.end()` and `next()` are also supported)
25
25
  - Helper functions for body parsing, cookie handling, redirects, headers and more
26
26
 
27
- Check out [the h3 docs](https://github.com/unjs/h3) for more information.
27
+ Check out [the h3 docs](https://github.com/h3js/h3) for more information.
28
28
 
29
29
  ::read-more{to="/docs/guide/directory-structure/server#server-routes"}
30
30
  Learn more about the API layer in the `server/` directory.
@@ -234,10 +234,6 @@ declare module 'vue' {
234
234
  export {}
235
235
  ```
236
236
 
237
- ::note
238
- If you are using WebStorm, you may need to augment `@vue/runtime-core` until [this issue](https://youtrack.jetbrains.com/issue/WEB-59818/VUE-TypeScript-WS-PS-does-not-correctly-display-type-of-globally-injected-properties) is resolved.
239
- ::
240
-
241
237
  ## Vue Plugins
242
238
 
243
239
  If you want to use Vue plugins, like [vue-gtag](https://github.com/MatteoGabriele/vue-gtag) to add Google Analytics tags, you can use a Nuxt plugin to do so.
@@ -101,7 +101,7 @@ export default defineNitroPlugin((nitroApp) => {
101
101
 
102
102
  ## Server Utilities
103
103
 
104
- Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
104
+ Server routes are powered by [h3js/h3](https://github.com/h3js/h3) which comes with a handy set of helpers.
105
105
 
106
106
  :read-more{to="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers" target="_blank"}
107
107
 
@@ -448,7 +448,7 @@ export default fromNodeMiddleware((req, res) => {
448
448
  ```
449
449
 
450
450
  ::important
451
- Legacy support is possible using [unjs/h3](https://github.com/unjs/h3), but it is advised to avoid legacy handlers as much as you can.
451
+ Legacy support is possible using [h3js/h3](https://github.com/h3js/h3), but it is advised to avoid legacy handlers as much as you can.
452
452
  ::
453
453
 
454
454
  ```ts [server/middleware/legacy.ts]
@@ -55,6 +55,10 @@ Since `.env` files are not used in production, you must explicitly set environme
55
55
 
56
56
  * Many cloud service providers, such as Vercel, Netlify, and AWS, provide interfaces for setting environment variables via their dashboards, CLI tools or configuration files.
57
57
 
58
+ ::important
59
+ `runtimeConfig` [won't pick up environment variables that don't start with `NUXT_` in production] (https://nuxt.com/docs/guide/going-further/runtime-config#environment-variables).
60
+ ::
61
+
58
62
  ## Production Preview
59
63
 
60
64
  For local production preview purpose, we recommend using [`nuxt preview`](/docs/api/commands/preview) since using this command, the `.env` file will be loaded into `process.env` for convenience. Note that this command requires dependencies to be installed in the package directory.
@@ -58,25 +58,6 @@ await nuxtApp.callHook('app:user:registered', {
58
58
  You can inspect all events using the **Nuxt DevTools** Hooks panel.
59
59
  ::
60
60
 
61
- ## Augmenting Types
62
-
63
- You can augment the types of hooks provided by Nuxt.
64
-
65
- ```ts
66
- import { HookResult } from "@nuxt/schema";
67
-
68
- declare module '#app' {
69
- interface RuntimeNuxtHooks {
70
- 'your-nuxt-runtime-hook': () => HookResult
71
- }
72
- interface NuxtHooks {
73
- 'your-nuxt-hook': () => HookResult
74
- }
75
- }
76
-
77
- declare module 'nitropack' {
78
- interface NitroRuntimeHooks {
79
- 'your-nitro-hook': () => void;
80
- }
81
- }
82
- ```
61
+ ::read-more{to="/docs/guide/going-further/hooks"}
62
+ Learn more about Nuxt's built-in hooks and how to extend them
63
+ ::
@@ -438,6 +438,7 @@ package-lock.json
438
438
  yarn.lock
439
439
  pnpm-lock.yaml
440
440
  tsconfig.json
441
+ bun.lock
441
442
  bun.lockb
442
443
  ```
443
444
 
@@ -32,7 +32,7 @@ Update `nuxt` dependency inside `package.json`:
32
32
  }
33
33
  ```
34
34
 
35
- Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
35
+ Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock` or `bun.lockb`) and reinstall dependencies.
36
36
 
37
37
  ## Opting Out
38
38
 
@@ -47,7 +47,7 @@ Update `nuxt` dependency inside `package.json`:
47
47
  }
48
48
  ```
49
49
 
50
- Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
50
+ Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock` or `bun.lockb`) and reinstall dependencies.
51
51
 
52
52
  ## Using Nightly `@nuxt/cli`
53
53
 
@@ -74,6 +74,25 @@ export default defineNitroPlugin((nitroApp) => {
74
74
  Learn more about available Nitro lifecycle hooks.
75
75
  ::
76
76
 
77
- ## Additional Hooks
77
+ ## Adding Custom Hooks
78
78
 
79
- Learn more about creating custom hooks in the [Events section](/docs/guide/going-further/events).
79
+ You can define your own custom hooks support by extending Nuxt's hook interfaces.
80
+
81
+ ```ts
82
+ import { HookResult } from "@nuxt/schema";
83
+
84
+ declare module '#app' {
85
+ interface RuntimeNuxtHooks {
86
+ 'your-nuxt-runtime-hook': () => HookResult
87
+ }
88
+ interface NuxtHooks {
89
+ 'your-nuxt-hook': () => HookResult
90
+ }
91
+ }
92
+
93
+ declare module 'nitropack' {
94
+ interface NitroRuntimeHooks {
95
+ 'your-nitro-hook': () => void;
96
+ }
97
+ }
98
+ ```
@@ -230,8 +230,6 @@ Learn more about asset injection in [the recipes section](#recipes).
230
230
  Published modules cannot leverage auto-imports for assets within their runtime directory. Instead, they have to import them explicitly from `#imports` or alike.
231
231
  :br :br
232
232
  Indeed, auto-imports are not enabled for files within `node_modules` (the location where a published module will eventually live) for performance reasons.
233
- :br :br
234
- If you are using the module starter, auto-imports will not be enabled in your playground either.
235
233
  ::
236
234
 
237
235
  ### Tooling
@@ -561,6 +559,31 @@ export default defineNuxtModule({
561
559
  ```
562
560
  ::
563
561
 
562
+ ##### Custom Hooks
563
+
564
+ Modules can also define and call their own hooks, which is a powerful pattern for making your module extensible.
565
+
566
+ If you expect other modules to be able to subscribe to your module's hooks, you should call them in the `modules:done` hook. This ensures that all other modules have had a chance to be set up and register their listeners to your hook during their own `setup` function.
567
+
568
+ ```ts
569
+ // my-module/module.ts
570
+ import { defineNuxtModule } from '@nuxt/kit'
571
+
572
+ export interface ModuleHooks {
573
+ 'my-module:custom-hook': (payload: { foo: string }) => void
574
+ }
575
+
576
+ export default defineNuxtModule({
577
+ setup (options, nuxt) {
578
+ // Call your hook in `modules:done`
579
+ nuxt.hook('modules:done', async () => {
580
+ const payload = { foo: 'bar' }
581
+ await nuxt.callHook('my-module:custom-hook', payload)
582
+ })
583
+ }
584
+ })
585
+ ```
586
+
564
587
  #### Adding Templates/Virtual Files
565
588
 
566
589
  If you need to add a virtual file that can be imported into the user's app, you can use the `addTemplate` utility.
@@ -51,6 +51,10 @@ In this example, we pass the `id` param to link to the route `~/pages/posts/[id]
51
51
  Check out the Pages panel in Nuxt DevTools to see the route name and the params it might take.
52
52
  ::
53
53
 
54
+ ::tip
55
+ When you pass an object into the `to` prop, `<NuxtLink>` will inherit Vue Router’s handling of query parameters. Keys and values will be automatically encoded, so you don’t need to call `encodeURI` or `encodeURIComponent` manually.
56
+ ::
57
+
54
58
  ### Handling Static File and Cross-App Links
55
59
 
56
60
  By default, `<NuxtLink>` uses Vue Router's client side navigation for relative route. When linking to static files in the `/public` directory or to another application hosted on the same domain, it might result in unexpected 404 errors because they are not part of the client routes. In such cases, you can use the `external` prop with `<NuxtLink>` to bypass Vue Router's internal routing mechanism.
@@ -12,23 +12,33 @@ links:
12
12
  This composable is available in Nuxt v3.12+.
13
13
  ::
14
14
 
15
- `onPrehydrate` is a composable lifecycle hook that allows you to run a callback on the client immediately before
16
- Nuxt hydrates the page.
17
-
15
+ `onPrehydrate` is a composable lifecycle hook that allows you to run a callback on the client immediately before Nuxt hydrates the page.
18
16
  ::note
19
17
  This is an advanced utility and should be used with care. For example, [`nuxt-time`](https://github.com/danielroe/nuxt-time/pull/251) and [`@nuxtjs/color-mode`](https://github.com/nuxt-modules/color-mode/blob/main/src/script.js) manipulate the DOM to avoid hydration mismatches.
20
18
  ::
21
19
 
22
20
  ## Usage
23
21
 
24
- `onPrehydrate` can be called directly in the setup function of a Vue component (for example, in `<script setup>`), or in a plugin.
25
- It will only have an effect when it is called on the server, and it will not be included in your client build.
22
+ Call `onPrehydrate` in the setup function of a Vue component (e.g., in `<script setup>`) or in a plugin. It only has an effect when called on the server and will not be included in your client build.
23
+
24
+ ## Type
25
+
26
+ ```ts [Signature]
27
+ export function onPrehydrate(callback: (el: HTMLElement) => void): void
28
+ export function onPrehydrate(callback: string | ((el: HTMLElement) => void), key?: string): undefined | string
29
+ ```
26
30
 
27
31
  ## Parameters
28
32
 
29
- - `callback`: A function that will be stringified and inlined in the HTML. It should not have any external
30
- dependencies (such as auto-imports) or refer to variables defined outside the callback. The callback will run
31
- before Nuxt runtime initializes so it should not rely on the Nuxt or Vue context.
33
+ | Parameter | Type | Required | Description |
34
+ | ---- | --- | --- | --- |
35
+ | `callback` | `((el: HTMLElement) => void) \| string` | Yes | A function (or stringified function) to run before Nuxt hydrates. It will be stringified and inlined in the HTML. Should not have external dependencies or reference variables outside the callback. Runs before Nuxt runtime initializes, so it should not rely on Nuxt or Vue context. |
36
+ | `key` | `string` | No | (Advanced) A unique key to identify the prehydrate script, useful for advanced scenarios like multiple root nodes. |
37
+
38
+ ## Return Values
39
+
40
+ - Returns `undefined` when called with only a callback function.
41
+ - Returns a string (the prehydrate id) when called with a callback and a key, which can be used to set or access the `data-prehydrate-id` attribute for advanced use cases.
32
42
 
33
43
  ## Example
34
44
 
@@ -36,19 +46,18 @@ before Nuxt runtime initializes so it should not rely on the Nuxt or Vue context
36
46
  <script setup lang="ts">
37
47
  declare const window: Window
38
48
  // ---cut---
39
- // onPrehydrate is guaranteed to run before Nuxt hydrates
49
+ // Run code before Nuxt hydrates
40
50
  onPrehydrate(() => {
41
51
  console.log(window)
42
52
  })
43
53
 
44
- // As long as it only has one root node, you can access the element
54
+ // Access the root element
45
55
  onPrehydrate((el) => {
46
56
  console.log(el.outerHTML)
47
57
  // <div data-v-inspector="app.vue:15:3" data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
48
58
  })
49
59
 
50
- // For _very_ advanced use cases (such as not having a single root node) you
51
- // can access/set `data-prehydrate-id` yourself
60
+ // Advanced: access/set `data-prehydrate-id` yourself
52
61
  const prehydrateId = onPrehydrate((el) => {})
53
62
  </script>
54
63
 
@@ -154,12 +154,12 @@ const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { imm
154
154
  - `pending`: the request is in progress
155
155
  - `success`: the request has completed successfully
156
156
  - `error`: the request has failed
157
- - `clear`: a function which will set `data` to `undefined`, set `error` to `null`, set `status` to `'idle'`, and mark any currently pending requests as cancelled.
157
+ - `clear`: a function that can be used to set `data` to `undefined` (or the value of `options.default()` if provided), set `error` to `null`, set `status` to `idle`, and mark any currently pending requests as cancelled.
158
158
 
159
159
  By default, Nuxt waits until a `refresh` is finished before it can be executed again.
160
160
 
161
161
  ::note
162
- If you have not fetched data on the server (for example, with `server: false`), then the data _will not_ be fetched until hydration completes. This means even if you await [`useAsyncData`](/docs/api/composables/use-async-data) on the client side, `data` will remain `null` within `<script setup>`.
162
+ If you have not fetched data on the server (for example, with `server: false`), then the data _will not_ be fetched until hydration completes. This means even if you await [`useAsyncData`](/docs/api/composables/use-async-data) on the client side, `data` will remain `undefined` within `<script setup>`.
163
163
  ::
164
164
 
165
165
  ## Type
@@ -170,7 +170,7 @@ function useAsyncData<DataT, DataE>(
170
170
  options?: AsyncDataOptions<DataT>
171
171
  ): AsyncData<DataT, DataE>
172
172
  function useAsyncData<DataT, DataE>(
173
- key: string | Ref<string> | ComputedRef<string>,
173
+ key: MaybeRefOrGetter<string>,
174
174
  handler: (nuxtApp?: NuxtApp) => Promise<DataT>,
175
175
  options?: AsyncDataOptions<DataT>
176
176
  ): Promise<AsyncData<DataT, DataE>>
@@ -184,7 +184,7 @@ type AsyncDataOptions<DataT> = {
184
184
  default?: () => DataT | Ref<DataT> | null
185
185
  transform?: (input: DataT) => DataT | Promise<DataT>
186
186
  pick?: string[]
187
- watch?: WatchSource[] | false
187
+ watch?: MultiWatchSources | false
188
188
  getCachedData?: (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined
189
189
  }
190
190
 
@@ -8,7 +8,9 @@ links:
8
8
  size: xs
9
9
  ---
10
10
 
11
- Within your pages, components and plugins you can use `useCookie`, an SSR-friendly composable to read and write cookies.
11
+ ## Usage
12
+
13
+ Within your pages, components, and plugins, you can use `useCookie` to read and write cookies in an SSR-friendly way.
12
14
 
13
15
  ```ts
14
16
  const cookie = useCookie(name, options)
@@ -19,144 +21,83 @@ const cookie = useCookie(name, options)
19
21
  ::
20
22
 
21
23
  ::tip
22
- `useCookie` ref will automatically serialize and deserialize cookie value to JSON.
24
+ The returned ref will automatically serialize and deserialize cookie values to JSON.
23
25
  ::
24
26
 
25
- ## Example
27
+ ## Type
26
28
 
27
- The example below creates a cookie called `counter`. If the cookie doesn't exist, it is initially set to a random value. Whenever we update the `counter` variable, the cookie will be updated accordingly.
29
+ ```ts [Signature]
30
+ import type { Ref } from 'vue'
31
+ import type { CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
28
32
 
29
- ```vue [app.vue]
30
- <script setup lang="ts">
31
- const counter = useCookie('counter')
33
+ export interface CookieOptions<T = any> extends Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'> {
34
+ decode?(value: string): T
35
+ encode?(value: T): string
36
+ default?: () => T | Ref<T>
37
+ watch?: boolean | 'shallow'
38
+ readonly?: boolean
39
+ }
32
40
 
33
- counter.value = counter.value || Math.round(Math.random() * 1000)
34
- </script>
41
+ export interface CookieRef<T> extends Ref<T> {}
35
42
 
36
- <template>
37
- <div>
38
- <h1>Counter: {{ counter || '-' }}</h1>
39
- <button @click="counter = null">reset</button>
40
- <button @click="counter--">-</button>
41
- <button @click="counter++">+</button>
42
- </div>
43
- </template>
43
+ export function useCookie<T = string | null | undefined>(
44
+ name: string,
45
+ options?: CookieOptions<T>
46
+ ): CookieRef<T>
44
47
  ```
45
48
 
46
- :link-example{to="/docs/examples/advanced/use-cookie"}
47
-
48
- ::note
49
- Refresh `useCookie` values manually when a cookie has changed with [`refreshCookie`](/docs/api/utils/refresh-cookie).
50
- ::
49
+ ## Parameters
51
50
 
52
- ## Options
51
+ `name`: The name of the cookie.
53
52
 
54
- Cookie composable accepts several options which let you modify the behavior of cookies.
53
+ `options`: Options to control cookie behavior. The object can have the following properties:
55
54
 
56
55
  Most of the options will be directly passed to the [cookie](https://github.com/jshttp/cookie) package.
57
56
 
58
- ### `maxAge` / `expires`
57
+ | Property | Type | Default | Description |
58
+ | --- | --- | --- | --- |
59
+ | `decode` | `(value: string) => T` | `decodeURIComponent` + [destr](https://github.com/unjs/destr). | Custom function to decode the cookie value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode a previously encoded cookie value into a JavaScript string or other object. <br/> **Note:** If an error is thrown from this function, the original, non-decoded cookie value will be returned as the cookie's value. |
60
+ | `encode` | `(value: T) => string` | `JSON.stringify` + `encodeURIComponent` | Custom function to encode the cookie value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value. |
61
+ | `default` | `() => T \| Ref<T>` | `undefined` | Function returning the default value if the cookie does not exist. The function can also return a `Ref`. |
62
+ | `watch` | `boolean \| 'shallow'` | `true` | Whether to watch for changes and update the cookie. `true` for deep watch, `'shallow'` for shallow watch, i.e. data changes for only top level properties, `false` to disable. <br/> **Note:** Refresh `useCookie` values manually when a cookie has changed with [`refreshCookie`](/docs/api/utils/refresh-cookie). |
63
+ | `readonly` | `boolean` | `false` | If `true`, disables writing to the cookie. |
64
+ | `maxAge` | `number` | `undefined` | Max age in seconds for the cookie, i.e. the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2). The given number will be converted to an integer by rounding down. By default, no maximum age is set. |
65
+ | `expires` | `Date` | `undefined` | Expiration date for the cookie. By default, no expiration is set. Most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application. <br/> **Note:** The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and `maxAge` is set, then `maxAge` takes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time! <br/>If neither of `expires` and `maxAge` is set, the cookie will be session-only and removed when the user closes their browser. |
66
+ | `httpOnly` | `boolean` | `false` | Sets the HttpOnly attribute. <br/> **Note:** Be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`. |
67
+ | `secure` | `boolean` | `false` | Sets the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5). <br/>**Note:** Be careful when setting this to `true`, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. This can lead to hydration errors. |
68
+ | `partitioned` | `boolean` | `false` | Sets the [`Partitioned` `Set-Cookie` attribute](https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1). <br/>**Note:** This is an attribute that has not yet been fully standardized, and may change in the future. <br/>This also means many clients may ignore this attribute until they understand it.<br/>More information can be found in the [proposal](https://github.com/privacycg/CHIPS). |
69
+ | `domain` | `string` | `undefined` | Sets the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3). By default, no domain is set, and most clients will consider applying the cookie only to the current domain. |
70
+ | `path` | `string` | `'/'` | Sets the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4). By default, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4). |
71
+ | `sameSite` | `boolean \| string` | `undefined` | Sets the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7). <br/>- `true` will set the `SameSite` attribute to `Strict` for strict same-site enforcement.<br/>- `false` will not set the `SameSite` attribute.<br/>- `'lax'` will set the `SameSite` attribute to `Lax` for lax same-site enforcement.<br/>- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.<br/>- `'strict'` will set the `SameSite` attribute to `Strict` for strict same-site enforcement. |
59
72
 
60
- Use these options to set the expiration of the cookie.
73
+ ## Return Values
61
74
 
62
- `maxAge`: Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.2).
63
- The given number will be converted to an integer by rounding down. By default, no maximum age is set.
75
+ Returns a Vue `Ref<T>` representing the cookie value. Updating the ref will update the cookie (unless `readonly` is set). The ref is SSR-friendly and will work on both client and server.
64
76
 
65
- `expires`: Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1).
66
- By default, no expiration is set. Most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
77
+ ## Examples
67
78
 
68
- ::note
69
- The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and `maxAge` is set, then `maxAge` takes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time!
70
- ::
71
-
72
- ::note
73
- If neither of `expires` and `maxAge` is set, the cookie will be session-only and removed when the user closes their browser.
74
- ::
75
-
76
- ### `httpOnly`
77
-
78
- Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6). When truthy, the `HttpOnly` attribute is set; otherwise it is not. By default, the `HttpOnly` attribute is not set.
79
-
80
- ::warning
81
- Be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
82
- ::
83
-
84
- ### `secure`
85
-
86
- Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5). When truthy, the `Secure` attribute is set; otherwise it is not. By default, the `Secure` attribute is not set.
87
-
88
- ::warning
89
- Be careful when setting this to `true`, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. This can lead to hydration errors.
90
- ::
91
-
92
- ### `partitioned`
93
-
94
- Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1) attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the `Partitioned` attribute is not set.
95
-
96
- ::note
97
- This is an attribute that has not yet been fully standardized, and may change in the future.
98
- This also means many clients may ignore this attribute until they understand it.
99
-
100
- More information can be found in the [proposal](https://github.com/privacycg/CHIPS).
101
- ::
79
+ ### Basic Usage
102
80
 
103
- ### `domain`
104
-
105
- Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3). By default, no domain is set, and most clients will consider applying the cookie only to the current domain.
106
-
107
- ### `path`
108
-
109
- Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4). By default, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4).
110
-
111
- ### `sameSite`
112
-
113
- Specifies the `boolean` or `string` value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7).
114
-
115
- - `true` will set the `SameSite` attribute to `Strict` for strict same-site enforcement.
116
- - `false` will not set the `SameSite` attribute.
117
- - `'lax'` will set the `SameSite` attribute to `Lax` for lax same-site enforcement.
118
- - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
119
- - `'strict'` will set the `SameSite` attribute to `Strict` for strict same-site enforcement.
120
-
121
- More information about the different enforcement levels can be found in [the specification](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7).
122
-
123
- ### `encode`
124
-
125
- Specifies a function that will be used to encode a cookie's value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.
126
-
127
- The default encoder is the `JSON.stringify` + `encodeURIComponent`.
128
-
129
- ### `decode`
130
-
131
- Specifies a function that will be used to decode a cookie's value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode a previously encoded cookie value into a JavaScript string or other object.
132
-
133
- The default decoder is `decodeURIComponent` + [destr](https://github.com/unjs/destr).
134
-
135
- ::note
136
- If an error is thrown from this function, the original, non-decoded cookie value will be returned as the cookie's value.
137
- ::
138
-
139
- ### `default`
140
-
141
- Specifies a function that returns the cookie's default value. The function can also return a `Ref`.
142
-
143
- ### `readonly`
144
-
145
- Allows _accessing_ a cookie value without the ability to set it.
146
-
147
- ### `watch`
81
+ The example below creates a cookie called `counter`. If the cookie doesn't exist, it is initially set to a random value. Whenever we update the `counter` variable, the cookie will be updated accordingly.
148
82
 
149
- Specifies the `boolean` or `string` value for [watch](https://vuejs.org/api/reactivity-core.html#watch) cookie ref data.
83
+ ```vue [app.vue]
84
+ <script setup lang="ts">
85
+ const counter = useCookie('counter')
150
86
 
151
- - `true` - Will watch cookie ref data changes and its nested properties (default).
152
- - `shallow` - Will watch cookie ref data changes for only top level properties
153
- - `false` - Will not watch cookie ref data changes.
87
+ counter.value = counter.value || Math.round(Math.random() * 1000)
88
+ </script>
154
89
 
155
- ::note
156
- Refresh `useCookie` values manually when a cookie has changed with [`refreshCookie`](/docs/api/utils/refresh-cookie).
157
- ::
90
+ <template>
91
+ <div>
92
+ <h1>Counter: {{ counter || '-' }}</h1>
93
+ <button @click="counter = null">reset</button>
94
+ <button @click="counter--">-</button>
95
+ <button @click="counter++">+</button>
96
+ </div>
97
+ </template>
98
+ ```
158
99
 
159
- **Example 1:**
100
+ ### Readonly Cookies
160
101
 
161
102
  ```vue
162
103
  <script setup lang="ts">
@@ -168,8 +109,9 @@ const user = useCookie(
168
109
  }
169
110
  )
170
111
 
171
- if (user.value && user.value !== null) {
172
- user.value.score++; // userInfo cookie not update with this change
112
+ if (user.value) {
113
+ // the actual `userInfo` cookie will not be updated
114
+ user.value.score++
173
115
  }
174
116
  </script>
175
117
 
@@ -178,7 +120,7 @@ if (user.value && user.value !== null) {
178
120
  </template>
179
121
  ```
180
122
 
181
- **Example 2:**
123
+ ### Writable Cookies
182
124
 
183
125
  ```vue
184
126
  <script setup lang="ts">
@@ -192,13 +134,13 @@ const list = useCookie(
192
134
 
193
135
  function add() {
194
136
  list.value?.push(Math.round(Math.random() * 1000))
195
- // list cookie not update with this change
137
+ // list cookie won't be updated with this change
196
138
  }
197
139
 
198
140
  function save() {
199
- if (list.value && list.value !== null) {
141
+ if (list.value) {
142
+ // the actual `list` cookie will be updated
200
143
  list.value = [...list.value]
201
- // list cookie update with this change
202
144
  }
203
145
  }
204
146
  </script>
@@ -213,9 +155,9 @@ function save() {
213
155
  </template>
214
156
  ```
215
157
 
216
- ## Cookies in API Routes
158
+ ### Cookies in API Routes
217
159
 
218
- You can use `getCookie` and `setCookie` from [`h3`](https://github.com/unjs/h3) package to set cookies in server API routes.
160
+ You can use `getCookie` and `setCookie` from [`h3`](https://github.com/h3js/h3) package to set cookies in server API routes.
219
161
 
220
162
  ```ts [server/api/counter.ts]
221
163
  export default defineEventHandler(event => {
@@ -8,25 +8,48 @@ links:
8
8
  size: xs
9
9
  ---
10
10
 
11
- The composable returns the global Nuxt error that is being handled and it is available on both client and server.
11
+ ## Usage
12
+
13
+ The `useError` composable returns the global Nuxt error that is being handled and is available on both client and server. It provides a reactive, SSR-friendly error state across your app.
12
14
 
13
15
  ```ts
14
16
  const error = useError()
15
17
  ```
16
18
 
17
- `useError` sets an error in the state and creates a reactive as well as SSR-friendly global Nuxt error across components.
19
+ You can use this composable in your components, pages, or plugins to access or react to the current Nuxt error.
18
20
 
19
- Nuxt errors have the following properties:
21
+ ## Type
20
22
 
21
23
  ```ts
22
- interface {
23
- // HTTP response status code
24
+ interface NuxtError<DataT = unknown> {
24
25
  statusCode: number
25
- // HTTP response status message
26
26
  statusMessage: string
27
- // Error message
28
27
  message: string
28
+ data?: DataT
29
+ error?: true
30
+ }
31
+
32
+ export const useError: () => Ref<NuxtError | undefined>
33
+ ```
34
+
35
+ ## Parameters
36
+
37
+ This composable does not take any parameters.
38
+
39
+ ## Return Values
40
+
41
+ Returns a `Ref` containing the current Nuxt error (or `undefined` if there is no error). The error object is reactive and will update automatically when the error state changes.
42
+
43
+ ## Example
44
+
45
+ ```ts
46
+ <script setup lang="ts">
47
+ const error = useError()
48
+
49
+ if (error.value) {
50
+ console.error('Nuxt error:', error.value)
29
51
  }
52
+ </script>
30
53
  ```
31
54
 
32
55
  :read-more{to="/docs/getting-started/error-handling"}
@@ -92,81 +92,8 @@ If you encounter the `data` variable destructured from a `useFetch` returns a st
92
92
 
93
93
  :video-accordion{title="Watch the video from Alexander Lichter to avoid using useFetch the wrong way" videoId="njsGVmcWviY"}
94
94
 
95
- :link-example{to="/docs/examples/advanced/use-custom-fetch-composable"}
96
-
97
95
  :read-more{to="/docs/getting-started/data-fetching"}
98
96
 
99
- :link-example{to="/docs/examples/features/data-fetching"}
100
-
101
- ## Params
102
-
103
- - `URL`: The URL to fetch.
104
- - `Options` (extends [unjs/ofetch](https://github.com/unjs/ofetch) options & [AsyncDataOptions](/docs/api/composables/use-async-data#params)):
105
- - `method`: Request method.
106
- - `query`: Adds query search params to URL using [ufo](https://github.com/unjs/ufo)
107
- - `params`: Alias for `query`
108
- - `body`: Request body - automatically stringified (if an object is passed).
109
- - `headers`: Request headers.
110
- - `baseURL`: Base URL for the request.
111
- - `timeout`: Milliseconds to automatically abort request
112
- - `cache`: Handles cache control according to [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/fetch#cache)
113
- - You can pass boolean to disable the cache or you can pass one of the following values: `default`, `no-store`, `reload`, `no-cache`, `force-cache`, and `only-if-cached`.
114
-
115
- ::note
116
- All fetch options can be given a `computed` or `ref` value. These will be watched and new requests made automatically with any new values if they are updated.
117
- ::
118
-
119
- - `Options` (from [`useAsyncData`](/docs/api/composables/use-async-data)):
120
- - `key`: a unique key to ensure that data fetching can be properly de-duplicated across requests, if not provided, it will be automatically generated based on URL and fetch options
121
- - `server`: whether to fetch the data on the server (defaults to `true`)
122
- - `lazy`: whether to resolve the async function after loading the route, instead of blocking client-side navigation (defaults to `false`)
123
- - `immediate`: when set to `false`, will prevent the request from firing immediately. (defaults to `true`)
124
- - `default`: a factory function to set the default value of the `data`, before the async function resolves - useful with the `lazy: true` or `immediate: false` option
125
- - `transform`: a function that can be used to alter `handler` function result after resolving
126
- - `getCachedData`: Provide a function which returns cached data. A `null` or `undefined` return value will trigger a fetch. By default, this is:
127
- ```ts
128
- const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating
129
- ? nuxtApp.payload.data[key]
130
- : nuxtApp.static.data[key]
131
- ```
132
- Which only caches data when `experimental.payloadExtraction` of `nuxt.config` is enabled.
133
- - `pick`: only pick specified keys in this array from the `handler` function result
134
- - `watch`: watch an array of reactive sources and auto-refresh the fetch result when they change. Fetch options and URL are watched by default. You can completely ignore reactive sources by using `watch: false`. Together with `immediate: false`, this allows for a fully-manual `useFetch`. (You can [see an example here](/docs/getting-started/data-fetching#watch) of using `watch`.)
135
- - `deep`: return data in a deep ref object (it is `true` by default). It can be set to `false` to return data in a shallow ref object, which can improve performance if your data does not need to be deeply reactive.
136
- - `dedupe`: avoid fetching same key more than once at a time (defaults to `cancel`). Possible options:
137
- - `cancel` - cancels existing requests when a new one is made
138
- - `defer` - does not make new requests at all if there is a pending request
139
-
140
- ::note
141
- If you provide a function or ref as the `url` parameter, or if you provide functions as arguments to the `options` parameter, then the `useFetch` call will not match other `useFetch` calls elsewhere in your codebase, even if the options seem to be identical. If you wish to force a match, you may provide your own key in `options`.
142
- ::
143
-
144
- ::note
145
- If you use `useFetch` to call an (external) HTTPS URL with a self-signed certificate in development, you will need to set `NODE_TLS_REJECT_UNAUTHORIZED=0` in your environment.
146
- ::
147
-
148
- :video-accordion{title="Watch a video from Alexander Lichter about client-side caching with getCachedData" videoId="aQPR0xn-MMk"}
149
-
150
- ## Return Values
151
-
152
- - `data`: the result of the asynchronous function that is passed in.
153
- - `refresh`/`execute`: a function that can be used to refresh the data returned by the `handler` function.
154
- - `error`: an error object if the data fetching failed.
155
- - `status`: a string indicating the status of the data request:
156
- - `idle`: when the request has not started, such as:
157
- - when `execute` has not yet been called and `{ immediate: false }` is set
158
- - when rendering HTML on the server and `{ server: false }` is set
159
- - `pending`: the request is in progress
160
- - `success`: the request has completed successfully
161
- - `error`: the request has failed
162
- - `clear`: a function which will set `data` to `undefined`, set `error` to `null`, set `status` to `'idle'`, and mark any currently pending requests as cancelled.
163
-
164
- By default, Nuxt waits until a `refresh` is finished before it can be executed again.
165
-
166
- ::note
167
- If you have not fetched data on the server (for example, with `server: false`), then the data _will not_ be fetched until hydration completes. This means even if you await `useFetch` on client-side, `data` will remain null within `<script setup>`.
168
- ::
169
-
170
97
  ## Type
171
98
 
172
99
  ```ts [Signature]
@@ -176,7 +103,7 @@ function useFetch<DataT, ErrorT>(
176
103
  ): Promise<AsyncData<DataT, ErrorT>>
177
104
 
178
105
  type UseFetchOptions<DataT> = {
179
- key?: string
106
+ key?: MaybeRefOrGetter<string>
180
107
  method?: string
181
108
  query?: SearchParams
182
109
  params?: SearchParams
@@ -192,7 +119,8 @@ type UseFetchOptions<DataT> = {
192
119
  default?: () => DataT
193
120
  transform?: (input: DataT) => DataT | Promise<DataT>
194
121
  pick?: string[]
195
- watch?: WatchSource[] | false
122
+ $fetch?: typeof globalThis.$fetch
123
+ watch?: MultiWatchSources | false
196
124
  }
197
125
 
198
126
  type AsyncDataRequestContext = {
@@ -215,3 +143,73 @@ interface AsyncDataExecuteOptions {
215
143
 
216
144
  type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
217
145
  ```
146
+
147
+ ## Parameters
148
+
149
+ - `URL` (`string | Request | Ref<string | Request> | () => string | Request`): The URL or request to fetch. Can be a string, a Request object, a Vue ref, or a function returning a string/Request. Supports reactivity for dynamic endpoints.
150
+
151
+ - `options` (object): Configuration for the fetch request. Extends [unjs/ofetch](https://github.com/unjs/ofetch) options and [`AsyncDataOptions`](/docs/api/composables/use-async-data#params). All options can be a static value, a `ref`, or a computed value.
152
+
153
+ | Option | Type | Default | Description |
154
+ | ---| --- | --- | --- |
155
+ | `key` | `MaybeRefOrGetter<string>` | auto-gen | Unique key for de-duplication. If not provided, generated from URL and options. |
156
+ | `method` | `string` | `'GET'` | HTTP request method. |
157
+ | `query` | `object` | - | Query/search params to append to the URL. Alias: `params`. Supports refs/computed. |
158
+ | `params` | `object` | - | Alias for `query`. |
159
+ | `body` | `RequestInit['body'] \| Record<string, any>` | - | Request body. Objects are automatically stringified. Supports refs/computed. |
160
+ | `headers` | `Record<string, string> \| [key, value][] \| Headers` | - | Request headers. |
161
+ | `baseURL` | `string` | - | Base URL for the request. |
162
+ | `timeout` | `number` | - | Timeout in milliseconds to abort the request. |
163
+ | `cache` | `boolean \| string` | - | Cache control. Boolean disables cache, or use Fetch API values: `default`, `no-store`, etc. |
164
+ | `server` | `boolean` | `true` | Whether to fetch on the server. |
165
+ | `lazy` | `boolean` | `false` | If true, resolves after route loads (does not block navigation). |
166
+ | `immediate` | `boolean` | `true` | If false, prevents request from firing immediately. |
167
+ | `default` | `() => DataT` | - | Factory for default value of `data` before async resolves. |
168
+ | `transform` | `(input: DataT) => DataT \| Promise<DataT>` | - | Function to transform the result after resolving. |
169
+ | `getCachedData`| `(key, nuxtApp, ctx) => DataT \| undefined` | - | Function to return cached data. See below for default. |
170
+ | `pick` | `string[]` | - | Only pick specified keys from the result. |
171
+ | `watch` | `MultiWatchSources \| false` | - | Array of reactive sources to watch and auto-refresh. `false` disables watching. |
172
+ | `deep` | `boolean` | `false` | Return data in a deep ref object. |
173
+ | `dedupe` | `'cancel' \| 'defer'` | `'cancel'` | Avoid fetching same key more than once at a time. |
174
+ | `$fetch` | `typeof globalThis.$fetch` | - | Custom $fetch implementation. |
175
+
176
+ ::note
177
+ All fetch options can be given a `computed` or `ref` value. These will be watched and new requests made automatically with any new values if they are updated.
178
+ ::
179
+
180
+ **getCachedData default:**
181
+
182
+ ```ts
183
+ const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating
184
+ ? nuxtApp.payload.data[key]
185
+ : nuxtApp.static.data[key]
186
+ ```
187
+ This only caches data when `experimental.payloadExtraction` in `nuxt.config` is enabled.
188
+
189
+ ## Return Values
190
+
191
+ | Name | Type | Description |
192
+ | --- | --- |--- |
193
+ | `data` | `Ref<DataT \| undefined>` | The result of the asynchronous fetch. |
194
+ | `refresh` | `(opts?: AsyncDataExecuteOptions) => Promise<void>` | Function to manually refresh the data. By default, Nuxt waits until a `refresh` is finished before it can be executed again. |
195
+ | `execute` | `(opts?: AsyncDataExecuteOptions) => Promise<void>` | Alias for `refresh`. |
196
+ | `error` | `Ref<ErrorT \| undefined>` | Error object if the data fetching failed. |
197
+ | `status` | `Ref<'idle' \| 'pending' \| 'success' \| 'error'>` | Status of the data request. See below for possible values. |
198
+ | `clear` | `() => void` | Resets `data` to `undefined` (or the value of `options.default()` if provided), `error` to `null`, set `status` to `idle`, and cancels any pending requests. |
199
+
200
+ ### Status values
201
+
202
+ - `idle`: Request has not started (e.g. `{ immediate: false }` or `{ server: false }` on server render)
203
+ - `pending`: Request is in progress
204
+ - `success`: Request completed successfully
205
+ - `error`: Request failed
206
+
207
+ ::note
208
+ If you have not fetched data on the server (for example, with `server: false`), then the data _will not_ be fetched until hydration completes. This means even if you await `useFetch` on client-side, `data` will remain null within `<script setup>`.
209
+ ::
210
+
211
+ ### Examples
212
+
213
+ :link-example{to="/docs/examples/advanced/use-custom-fetch-composable"}
214
+
215
+ :link-example{to="/docs/examples/features/data-fetching"}
@@ -95,7 +95,7 @@ Some useful methods:
95
95
 
96
96
  Nuxt exposes the following properties through `ssrContext`:
97
97
  - `url` (string) - Current request url.
98
- - `event` ([unjs/h3](https://github.com/unjs/h3) request event) - Access the request & response of the current route.
98
+ - `event` ([h3js/h3](https://github.com/h3js/h3) request event) - Access the request & response of the current route.
99
99
  - `payload` (object) - NuxtApp payload object.
100
100
 
101
101
  ### `payload`
@@ -108,5 +108,5 @@ async function addTodo () {
108
108
  ## Type
109
109
 
110
110
  ```ts
111
- useNuxtData<DataT = any> (key: string): { data: Ref<DataT | undefined> }
111
+ useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null> }
112
112
  ```
@@ -55,7 +55,7 @@ Variables that need to be accessible on the server are added directly inside `ru
55
55
  To access runtime config, we can use `useRuntimeConfig()` composable:
56
56
 
57
57
  ```ts [server/api/test.ts]
58
- export default defineEventHandler((event) => {
58
+ export default defineEventHandler(async (event) => {
59
59
  const config = useRuntimeConfig(event)
60
60
 
61
61
  // Access public variables
@@ -0,0 +1,102 @@
1
+ ---
2
+ title: "defineNuxtPlugin"
3
+ description: defineNuxtPlugin() is a helper function for creating Nuxt plugins.
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts
8
+ size: xs
9
+ ---
10
+
11
+ `defineNuxtPlugin` is a helper function for creating Nuxt plugins with enhanced functionality and type safety. This utility normalizes different plugin formats into a consistent structure that works seamlessly within Nuxt's plugin system.
12
+
13
+ ```ts twoslash [plugins/hello.ts]
14
+ export default defineNuxtPlugin((nuxtApp) => {
15
+ // Doing something with nuxtApp
16
+ })
17
+ ```
18
+
19
+ :read-more{to="/docs/guide/directory-structure/plugins#creating-plugins"}
20
+
21
+ ## Type
22
+
23
+ ```ts
24
+ defineNuxtPlugin<T extends Record<string, unknown>>(plugin: Plugin<T> | ObjectPlugin<T>): Plugin<T> & ObjectPlugin<T>
25
+
26
+ type Plugin<T> = (nuxt: [NuxtApp](/docs/guide/going-further/internals#the-nuxtapp-interface)) => Promise<void> | Promise<{ provide?: T }> | void | { provide?: T }
27
+
28
+ interface ObjectPlugin<T> {
29
+ name?: string
30
+ enforce?: 'pre' | 'default' | 'post'
31
+ dependsOn?: string[]
32
+ order?: number
33
+ parallel?: boolean
34
+ setup?: Plugin<T>
35
+ hooks?: Partial<[RuntimeNuxtHooks](/docs/api/advanced/hooks#app-hooks-runtime)>
36
+ env?: {
37
+ islands?: boolean
38
+ }
39
+ }
40
+ ```
41
+
42
+ ## Parameters
43
+
44
+ **plugin**: A plugin can be defined in two ways:
45
+ 1. **Function Plugin**: A function that receives the [`NuxtApp`](/docs/guide/going-further/internals#the-nuxtapp-interface) instance and can return a promise with an potential object with a [`provide`](/docs/guide/directory-structure/plugins#providing-helpers) property if you want to provide a helper on [`NuxtApp`](/docs/guide/going-further/internals#the-nuxtapp-interface) instance.
46
+ 2. **Object Plugin**: An object that can include various properties to configure the plugin's behavior, such as `name`, `enforce`, `dependsOn`, `order`, `parallel`, `setup`, `hooks`, and `env`.
47
+
48
+ | Property | Type | Required | Description |
49
+ | ------------------ | -------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- |
50
+ | `name` | `string` | `false` | Optional name for the plugin, useful for debugging and dependency management. |
51
+ | `enforce` | `'pre'` \| `'default'` \| `'post'` | `false` | Controls when the plugin runs relative to other plugins. |
52
+ | `dependsOn` | `string[]` | `false` | Array of plugin names this plugin depends on. Ensures proper execution order. |
53
+ | `order` | `number` | `false` | This allows more granular control over plugin order and should only be used by advanced users. **It overrides the value of `enforce` and is used to sort plugins.** |
54
+ | `parallel` | `boolean` | `false` | Whether to execute the plugin in parallel with other parallel plugins. |
55
+ | `setup` | `Plugin<T>`{lang="ts"} | `false` | The main plugin function, equivalent to a function plugin. |
56
+ | `hooks` | `Partial<RuntimeNuxtHooks>`{lang="ts"} | `false` | Nuxt app runtime hooks to register directly. |
57
+ | `env` | `{ islands?: boolean }`{lang="ts"} | `false` | Set this value to `false` if you don't want the plugin to run when rendering server-only or island components. |
58
+
59
+ :video-accordion{title="Watch a video from Alexander Lichter about the Object Syntax for Nuxt plugins" videoId="2aXZyXB1QGQ"}
60
+
61
+ ## Examples
62
+
63
+ ### Basic Usage
64
+
65
+ The example below demonstrates a simple plugin that adds global functionality:
66
+
67
+ ```ts twoslash [plugins/hello.ts]
68
+ export default defineNuxtPlugin((nuxtApp) => {
69
+ // Add a global method
70
+ return {
71
+ provide: {
72
+ hello: (name: string) => `Hello ${name}!`
73
+ }
74
+ }
75
+ })
76
+ ```
77
+
78
+ ### Object Syntax Plugin
79
+
80
+ The example below shows the object syntax with advanced configuration:
81
+
82
+ ```ts twoslash [plugins/advanced.ts]
83
+ export default defineNuxtPlugin({
84
+ name: 'my-plugin',
85
+ enforce: 'pre',
86
+ async setup (nuxtApp) {
87
+ // Plugin setup logic
88
+ const data = await $fetch('/api/config')
89
+
90
+ return {
91
+ provide: {
92
+ config: data
93
+ }
94
+ }
95
+ },
96
+ hooks: {
97
+ 'app:created'() {
98
+ console.log('App created!')
99
+ }
100
+ },
101
+ })
102
+ ```
@@ -36,7 +36,7 @@ function useLogger (tag?: string, options?: Partial<ConsolaOptions>): ConsolaIns
36
36
 
37
37
  ### Parameters
38
38
 
39
- **`tag`**: A tag to suffix all log messages with.
39
+ **`tag`**: A tag to suffix all log messages with, displayed on the right near the timestamp.
40
40
 
41
41
  **`options`**: Consola configuration options.
42
42
 
@@ -95,11 +95,11 @@ See [Nitro](https://nitro.build/guide/plugins#available-hooks) for all available
95
95
  Hook | Arguments | Description | Types
96
96
  -----------------------|-----------------------|--------------------------------------|------------------
97
97
  `dev:ssr-logs` | `{ path, logs }` | Server | Called at the end of a request cycle with an array of server-side logs.
98
- `render:response` | `response, { event }` | Called before sending the response. | [response](https://github.com/nuxt/nuxt/blob/71ef8bd3ff207fd51c2ca18d5a8c7140476780c7/packages/nuxt/src/core/runtime/nitro/renderer.ts#L24), [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
99
- `render:html` | `html, { event }` | Called before constructing the HTML. | [html](https://github.com/nuxt/nuxt/blob/71ef8bd3ff207fd51c2ca18d5a8c7140476780c7/packages/nuxt/src/core/runtime/nitro/renderer.ts#L15), [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
100
- `render:island` | `islandResponse, { event, islandContext }` | Called before constructing the island HTML. | [islandResponse](https://github.com/nuxt/nuxt/blob/e50cabfed1984c341af0d0c056a325a8aec26980/packages/nuxt/src/core/runtime/nitro/renderer.ts#L28), [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), [islandContext](https://github.com/nuxt/nuxt/blob/e50cabfed1984c341af0d0c056a325a8aec26980/packages/nuxt/src/core/runtime/nitro/renderer.ts#L38)
98
+ `render:response` | `response, { event }` | Called before sending the response. | [response](https://github.com/nuxt/nuxt/blob/71ef8bd3ff207fd51c2ca18d5a8c7140476780c7/packages/nuxt/src/core/runtime/nitro/renderer.ts#L24), [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
99
+ `render:html` | `html, { event }` | Called before constructing the HTML. | [html](https://github.com/nuxt/nuxt/blob/71ef8bd3ff207fd51c2ca18d5a8c7140476780c7/packages/nuxt/src/core/runtime/nitro/renderer.ts#L15), [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
100
+ `render:island` | `islandResponse, { event, islandContext }` | Called before constructing the island HTML. | [islandResponse](https://github.com/nuxt/nuxt/blob/e50cabfed1984c341af0d0c056a325a8aec26980/packages/nuxt/src/core/runtime/nitro/renderer.ts#L28), [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), [islandContext](https://github.com/nuxt/nuxt/blob/e50cabfed1984c341af0d0c056a325a8aec26980/packages/nuxt/src/core/runtime/nitro/renderer.ts#L38)
101
101
  `close` | - | Called when Nitro is closed. | -
102
- `error` | `error, { event? }` | Called when an error occurs. | [error](https://github.com/nitrojs/nitro/blob/d20ffcbd16fc4003b774445e1a01e698c2bb078a/src/types/runtime/nitro.ts#L48), [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
103
- `request` | `event` | Called when a request is received. | [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
104
- `beforeResponse` | `event, { body }` | Called before sending the response. | [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), unknown
105
- `afterResponse` | `event, { body }` | Called after sending the response. | [event](https://github.com/unjs/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), unknown
102
+ `error` | `error, { event? }` | Called when an error occurs. | [error](https://github.com/nitrojs/nitro/blob/d20ffcbd16fc4003b774445e1a01e698c2bb078a/src/types/runtime/nitro.ts#L48), [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
103
+ `request` | `event` | Called when a request is received. | [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38)
104
+ `beforeResponse` | `event, { body }` | Called before sending the response. | [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), unknown
105
+ `afterResponse` | `event, { body }` | Called after sending the response. | [event](https://github.com/h3js/h3/blob/f6ceb5581043dc4d8b6eab91e9be4531e0c30f8e/src/types.ts#L38), unknown
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs",
3
- "version": "3.17.5",
3
+ "version": "3.17.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",