@nuxt/docs 3.17.4 → 3.17.6

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.
Files changed (63) hide show
  1. package/1.getting-started/01.introduction.md +3 -3
  2. package/1.getting-started/03.configuration.md +1 -1
  3. package/1.getting-started/07.routing.md +1 -1
  4. package/1.getting-started/10.data-fetching.md +1 -1
  5. package/1.getting-started/11.state-management.md +1 -1
  6. package/1.getting-started/12.error-handling.md +1 -1
  7. package/1.getting-started/13.server.md +1 -1
  8. package/1.getting-started/15.prerendering.md +8 -8
  9. package/1.getting-started/16.deployment.md +2 -2
  10. package/1.getting-started/18.upgrade.md +7 -7
  11. package/2.guide/1.concepts/10.nuxt-lifecycle.md +14 -4
  12. package/2.guide/1.concepts/3.rendering.md +2 -2
  13. package/2.guide/1.concepts/4.server-engine.md +2 -2
  14. package/2.guide/1.concepts/5.modules.md +1 -1
  15. package/2.guide/1.concepts/8.typescript.md +6 -6
  16. package/2.guide/1.concepts/9.code-style.md +1 -1
  17. package/2.guide/2.directory-structure/1.composables.md +1 -1
  18. package/2.guide/2.directory-structure/1.content.md +1 -1
  19. package/2.guide/2.directory-structure/1.pages.md +5 -1
  20. package/2.guide/2.directory-structure/1.plugins.md +0 -4
  21. package/2.guide/2.directory-structure/1.server.md +3 -3
  22. package/2.guide/2.directory-structure/2.env.md +4 -4
  23. package/2.guide/3.going-further/1.experimental-features.md +2 -1
  24. package/2.guide/3.going-further/1.internals.md +2 -2
  25. package/2.guide/3.going-further/10.runtime-config.md +1 -1
  26. package/2.guide/3.going-further/11.nightly-release-channel.md +4 -8
  27. package/2.guide/3.going-further/3.modules.md +2 -4
  28. package/2.guide/3.going-further/9.debugging.md +1 -5
  29. package/2.guide/4.recipes/4.sessions-and-authentication.md +3 -3
  30. package/3.api/1.components/10.nuxt-picture.md +1 -1
  31. package/3.api/1.components/4.nuxt-link.md +4 -0
  32. package/3.api/1.components/9.nuxt-img.md +1 -1
  33. package/3.api/2.composables/on-prehydrate.md +21 -12
  34. package/3.api/2.composables/use-async-data.md +1 -1
  35. package/3.api/2.composables/use-cookie.md +67 -125
  36. package/3.api/2.composables/use-error.md +30 -7
  37. package/3.api/2.composables/use-fetch.md +70 -73
  38. package/3.api/2.composables/use-nuxt-app.md +1 -1
  39. package/3.api/2.composables/use-preview-mode.md +3 -3
  40. package/3.api/3.utils/define-nuxt-plugin.md +102 -0
  41. package/3.api/4.commands/add.md +20 -20
  42. package/3.api/4.commands/analyze.md +2 -2
  43. package/3.api/4.commands/build-module.md +2 -2
  44. package/3.api/4.commands/build.md +2 -2
  45. package/3.api/4.commands/cleanup.md +2 -2
  46. package/3.api/4.commands/dev.md +3 -3
  47. package/3.api/4.commands/devtools.md +3 -3
  48. package/3.api/4.commands/generate.md +3 -3
  49. package/3.api/4.commands/info.md +2 -2
  50. package/3.api/4.commands/init.md +3 -3
  51. package/3.api/4.commands/module.md +8 -8
  52. package/3.api/4.commands/prepare.md +2 -2
  53. package/3.api/4.commands/preview.md +3 -3
  54. package/3.api/4.commands/typecheck.md +2 -2
  55. package/3.api/4.commands/upgrade.md +2 -2
  56. package/3.api/5.kit/13.logging.md +1 -1
  57. package/3.api/5.kit/7.pages.md +1 -1
  58. package/3.api/6.advanced/1.hooks.md +8 -8
  59. package/5.community/4.contribution.md +1 -1
  60. package/5.community/6.roadmap.md +17 -12
  61. package/5.community/7.changelog.md +1 -1
  62. package/7.migration/2.configuration.md +2 -2
  63. package/package.json +1 -1
@@ -21,7 +21,7 @@ links:
21
21
  In order to use `<NuxtImg>` you should install and enable the Nuxt Image module:
22
22
 
23
23
  ```bash [Terminal]
24
- npx nuxi@latest module add image
24
+ npx nuxt module add image
25
25
  ```
26
26
 
27
27
  ## Usage
@@ -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,7 +154,7 @@ 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
 
@@ -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]
@@ -215,3 +142,73 @@ interface AsyncDataExecuteOptions {
215
142
 
216
143
  type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
217
144
  ```
145
+
146
+ ## Parameters
147
+
148
+ - `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.
149
+
150
+ - `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.
151
+
152
+ | Option | Type | Default | Description |
153
+ | ---| --- | --- | --- |
154
+ | `key` | `string` | auto-gen | Unique key for de-duplication. If not provided, generated from URL and options. |
155
+ | `method` | `string` | `'GET'` | HTTP request method. |
156
+ | `query` | `object` | - | Query/search params to append to the URL. Alias: `params`. Supports refs/computed. |
157
+ | `params` | `object` | - | Alias for `query`. |
158
+ | `body` | `RequestInit['body'] \| Record<string, any>` | - | Request body. Objects are automatically stringified. Supports refs/computed. |
159
+ | `headers` | `Record<string, string> \| [key, value][] \| Headers` | - | Request headers. |
160
+ | `baseURL` | `string` | - | Base URL for the request. |
161
+ | `timeout` | `number` | - | Timeout in milliseconds to abort the request. |
162
+ | `cache` | `boolean \| string` | - | Cache control. Boolean disables cache, or use Fetch API values: `default`, `no-store`, etc. |
163
+ | `server` | `boolean` | `true` | Whether to fetch on the server. |
164
+ | `lazy` | `boolean` | `false` | If true, resolves after route loads (does not block navigation). |
165
+ | `immediate` | `boolean` | `true` | If false, prevents request from firing immediately. |
166
+ | `default` | `() => DataT` | - | Factory for default value of `data` before async resolves. |
167
+ | `transform` | `(input: DataT) => DataT \| Promise<DataT>` | - | Function to transform the result after resolving. |
168
+ | `getCachedData`| `(key, nuxtApp, ctx) => DataT \| undefined` | - | Function to return cached data. See below for default. |
169
+ | `pick` | `string[]` | - | Only pick specified keys from the result. |
170
+ | `watch` | `WatchSource[] \| false` | - | Array of reactive sources to watch and auto-refresh. `false` disables watching. |
171
+ | `deep` | `boolean` | `false` | Return data in a deep ref object. |
172
+ | `dedupe` | `'cancel' \| 'defer'` | `'cancel'` | Avoid fetching same key more than once at a time. |
173
+ | `$fetch` | `typeof $fetch` | - | Custom $fetch implementation. |
174
+
175
+ ::note
176
+ 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.
177
+ ::
178
+
179
+ **getCachedData default:**
180
+
181
+ ```ts
182
+ const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating
183
+ ? nuxtApp.payload.data[key]
184
+ : nuxtApp.static.data[key]
185
+ ```
186
+ This only caches data when `experimental.payloadExtraction` in `nuxt.config` is enabled.
187
+
188
+ ## Return Values
189
+
190
+ | Name | Type | Description |
191
+ | --- | --- |--- |
192
+ | `data` | `Ref<DataT \| null>` | The result of the asynchronous fetch. |
193
+ | `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. |
194
+ | `execute` | `(opts?: AsyncDataExecuteOptions) => Promise<void>` | Alias for `refresh`. |
195
+ | `error` | `Ref<ErrorT \| null>` | Error object if the data fetching failed. |
196
+ | `status` | `Ref<'idle' \| 'pending' \| 'success' \| 'error'>` | Status of the data request. See below for possible values. |
197
+ | `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. |
198
+
199
+ ### Status values
200
+
201
+ - `idle`: Request has not started (e.g. `{ immediate: false }` or `{ server: false }` on server render)
202
+ - `pending`: Request is in progress
203
+ - `success`: Request completed successfully
204
+ - `error`: Request failed
205
+
206
+ ::note
207
+ 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>`.
208
+ ::
209
+
210
+ ### Examples
211
+
212
+ :link-example{to="/docs/examples/advanced/use-custom-fetch-composable"}
213
+
214
+ :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`
@@ -103,8 +103,8 @@ const { data } = await useFetch('/api/preview', {
103
103
  Now you can generate your site and serve it:
104
104
 
105
105
  ```bash [Terminal]
106
- npx nuxi generate
107
- npx nuxi preview
106
+ npx nuxt generate
107
+ npx nuxt preview
108
108
  ```
109
109
 
110
110
  Then you can see your preview page by adding the query param `preview` to the end of the page you want to see once:
@@ -114,5 +114,5 @@ Then you can see your preview page by adding the query param `preview` to the en
114
114
  ```
115
115
 
116
116
  ::note
117
- `usePreviewMode` should be tested locally with `nuxi generate` and then `nuxi preview` rather than `nuxi dev`. (The [preview command](/docs/api/commands/preview) is not related to preview mode.)
117
+ `usePreviewMode` should be tested locally with `nuxt generate` and then `nuxt preview` rather than `nuxt dev`. (The [preview command](/docs/api/commands/preview) is not related to preview mode.)
118
118
  ::