@nuxt/docs-nightly 4.0.0-29178461.f99b7b01 → 4.0.0-29179457.2dafcc72

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 `undefined`, 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
 
@@ -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.
@@ -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]
@@ -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
@@ -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,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 `undefined`, 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">
@@ -179,7 +120,7 @@ if (user.value) {
179
120
  </template>
180
121
  ```
181
122
 
182
- **Example 2:**
123
+ ### Writable Cookies
183
124
 
184
125
  ```vue
185
126
  <script setup lang="ts">
@@ -193,7 +134,7 @@ const list = useCookie(
193
134
 
194
135
  function add() {
195
136
  list.value?.push(Math.round(Math.random() * 1000))
196
- // list cookie not update with this change
137
+ // list cookie won't be updated with this change
197
138
  }
198
139
 
199
140
  function save() {
@@ -214,9 +155,9 @@ function save() {
214
155
  </template>
215
156
  ```
216
157
 
217
- ## Cookies in API Routes
158
+ ### Cookies in API Routes
218
159
 
219
- 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.
220
161
 
221
162
  ```ts [server/api/counter.ts]
222
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 `false` by default 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 `undefined`, 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`
@@ -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
+ ```
@@ -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-nightly",
3
- "version": "4.0.0-29178461.f99b7b01",
3
+ "version": "4.0.0-29179457.2dafcc72",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",