@nuxt/docs-nightly 5.0.0-2610051152-6240b79 → 5.0.0-2610051235-e7973c0
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.
|
@@ -520,12 +520,12 @@ export default defineNuxtConfig({
|
|
|
520
520
|
|
|
521
521
|
#### What Changed
|
|
522
522
|
|
|
523
|
-
Nuxt 5 ships `nuxt/server`, an import surface for the server utilities server code reaches for most: `defineEventHandler`, `createError`, `getQuery`, `readBody`, the cookie and header helpers, `sendRedirect`, `getRouteRules` and `useRuntimeConfig`.
|
|
523
|
+
Nuxt 5 ships `nuxt/server`, an import surface for the server utilities server code reaches for most: `defineEventHandler`, `createError`, `getQuery`, `readBody`, the cookie and header helpers, `sendRedirect`, `getRouteRules` and `useRuntimeConfig`.
|
|
524
524
|
|
|
525
|
-
|
|
525
|
+
In Nuxt 4, server code imports these from `h3` or gets them as auto-imports, which ties it to h3 v1 and `nitropack`. Importing from `nuxt/server` instead works with whichever [`server.builder`](/docs/guide/going-further/builders) is configured, so one file can serve Nuxt 4.6 (running either `nitropack` v2 or Nitro v3) and Nuxt 5.
|
|
526
526
|
|
|
527
527
|
```diff [server/api/hello.ts]
|
|
528
|
-
- import { defineEventHandler, getQuery } from '
|
|
528
|
+
- import { defineEventHandler, getQuery } from 'h3'
|
|
529
529
|
+ import { defineEventHandler, getQuery } from 'nuxt/server'
|
|
530
530
|
|
|
531
531
|
export default defineEventHandler((event) => {
|
|
@@ -533,25 +533,47 @@ Which server runtime is under your application depends on the configured [`serve
|
|
|
533
533
|
})
|
|
534
534
|
```
|
|
535
535
|
|
|
536
|
-
Errors take the same shape as the ones the Vue part of your app constructs
|
|
536
|
+
Errors take the same shape as the ones the Vue part of your app constructs:
|
|
537
537
|
|
|
538
538
|
```diff
|
|
539
|
-
- import {
|
|
539
|
+
- import { createError } from 'h3'
|
|
540
540
|
+ import { createError } from 'nuxt/server'
|
|
541
541
|
|
|
542
542
|
export default defineEventHandler(() => {
|
|
543
|
-
- throw
|
|
543
|
+
- throw createError({ statusCode: 400, statusMessage: 'Bad request' })
|
|
544
544
|
+ throw createError({ status: 400, statusText: 'Bad request' })
|
|
545
545
|
})
|
|
546
546
|
```
|
|
547
547
|
|
|
548
|
-
Server auto-imports
|
|
548
|
+
Server auto-imports are [off by default in Nuxt 5](#server-auto-imports-are-now-opt-in). A project that enables them with `experimental.nitroAutoImports` gets `nuxt/server` through them, so it needs no import changes.
|
|
549
549
|
|
|
550
550
|
#### Migration Steps
|
|
551
551
|
|
|
552
|
-
1. Replace `
|
|
553
|
-
2.
|
|
554
|
-
3.
|
|
552
|
+
1. Replace `h3` imports with `nuxt/server`, for the utilities in [the surface](/docs/guide/going-further/server-imports#types-and-utilities).
|
|
553
|
+
2. Import anything else from `nitro/h3`. `nuxt/server` is not a re-export of h3, so helpers such as `proxyRequest` are not part of it.
|
|
554
|
+
3. Update calls affected by the [differences from h3 v1](#differences-from-h3-v1), whether the helpers are imported or auto-imported.
|
|
555
|
+
|
|
556
|
+
#### Differences From h3 v1
|
|
557
|
+
|
|
558
|
+
| h3 v1 | `nuxt/server` |
|
|
559
|
+
|---|---|
|
|
560
|
+
| `sendRedirect(event, location)` sends the response. | Returns the response body: `return sendRedirect(event, '/login')`. |
|
|
561
|
+
| `getRouterParam(event, name)` and `getRouterParams(event)` return decoded values. | They return values as they appear in the URL. Pass `{ decode: true }` to decode them. |
|
|
562
|
+
| `handleCors(event, options)` returns `true` when it answered a preflight request. | Returns the preflight `Response`, or `false`: `const preflight = handleCors(event, options); if (preflight) return preflight`. |
|
|
563
|
+
| `handleCors` accepts a single origin string at runtime. | `origin` is `'*'`, `'null'`, an array of origins or patterns, or a function: wrap a single origin in an array. `maxAge` is a string of seconds, such as `'86400'`, or `false`. Import the `CorsOptions` type from `nuxt/server`. |
|
|
564
|
+
| `readValidatedBody` and `getValidatedQuery` take a validation function. | They take a [Standard Schema](https://standardschema.dev) or a function. |
|
|
565
|
+
| `createError({ statusCode, statusMessage })` | `createError({ status, statusText })` |
|
|
566
|
+
| `isError(error)` | `isNuxtError(error)` |
|
|
567
|
+
| h3's `useSession`, `getSession`, `updateSession` and `clearSession` seal an `h3` cookie with the `password` you pass. | They seal a `nuxt-session` cookie, by default with a secret derived from `appSecret`. A session one issues does not unseal with the other, so users get a new session once. See [Sessions Come From `nuxt/server`](#sessions-come-from-nuxtserver). |
|
|
568
|
+
| `useRuntimeConfig(event)` | `useRuntimeConfig()`. There is no per-request form. |
|
|
569
|
+
| Global `$fetch` | Not part of `nuxt/server`. Call a route of the app with `serverFetch(event, path)`, which returns a `Response`. For other URLs, plain `fetch` does not throw on a non-2xx status and does not parse JSON: check `response.ok` and call `response.json()`. |
|
|
570
|
+
| `event.path` | `getRequestURL(event).pathname`, or `event.url.pathname`. |
|
|
571
|
+
| `event.node` | Not available. Use `event.req` and `event.res`. |
|
|
572
|
+
| `getResponseHeader`, `setResponseHeader`, `appendResponseHeader`, `removeResponseHeader` | `event.res.headers.get()`, `.set()`, `.append()`, `.delete()` |
|
|
573
|
+
| `getMethod(event)`, `isMethod(event, method)`, `assertMethod(event, method)` | Compare `event.req.method`. |
|
|
574
|
+
| `readMultipartFormData(event)` | `await event.req.formData()` |
|
|
575
|
+
| `readRawBody(event)`, `getRequestWebStream(event)` | `await event.req.arrayBuffer()` (or `.text()`), `event.req.body` |
|
|
576
|
+
| `sanitizeStatusCode` | Not provided. |
|
|
555
577
|
|
|
556
578
|
::read-more{to="/docs/guide/going-further/server-imports"}
|
|
557
579
|
Learn what the surface covers, and what it means for module authors.
|
|
@@ -56,7 +56,7 @@ export default defineNuxtModule({
|
|
|
56
56
|
})
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
The two files differ in their imports, and wherever the handler uses an h3 v1 helper or behavior that `nuxt/server` handles differently:
|
|
60
60
|
|
|
61
61
|
::code-group
|
|
62
62
|
|
|
@@ -80,13 +80,17 @@ export default defineEventHandler(event => ({
|
|
|
80
80
|
|
|
81
81
|
::
|
|
82
82
|
|
|
83
|
+
::read-more{to="/docs/getting-started/upgrade#differences-from-h3-v1"}
|
|
84
|
+
See every difference between h3 v1 and `nuxt/server`, and what to use instead.
|
|
85
|
+
::
|
|
86
|
+
|
|
83
87
|
The keys indicate which server API each file relies upon:
|
|
84
88
|
|
|
85
89
|
| Key | The file imports | Where it runs |
|
|
86
90
|
|---|---|---|
|
|
87
91
|
| `nuxt` | `nuxt/server` only | Any server builder, from Nuxt 4.6 |
|
|
88
92
|
| `nitro2` | `h3`, `nitropack/runtime`, `#imports` | `nitropack` v2 directly, Nitro v3 through the compatibility layer |
|
|
89
|
-
| `nitro3` | `nitro`, `nitro/h3` | The Nitro server builder, v3 |
|
|
93
|
+
| `nitro3` | `nitro`, `nitro/h3`, alone or alongside `nuxt/server` | The Nitro server builder, v3 |
|
|
90
94
|
|
|
91
95
|
Nuxt will pick the most appropriate handler to use based on the server builder a user is using. If you register a handler which the user's server builder cannot run, it will be skipped with a warning.
|
|
92
96
|
|
|
@@ -97,9 +101,23 @@ Use `nitro3` only for code that needs an API only Nitro v3 offers. Using `nuxt/s
|
|
|
97
101
|
Using this pattern means you will support both old (<4.6) and new versions of Nuxt (including Nuxt 5).
|
|
98
102
|
|
|
99
103
|
::important
|
|
100
|
-
|
|
104
|
+
The object form of `handler` needs `@nuxt/kit@^4.6` in your module's `dependencies`, which is what the [module starter](/docs/guide/modules/getting-started) sets up. If `@nuxt/kit` is only a `devDependency` and left external when you build, or is a `peerDependency`, the application's version runs instead, and a version older than 4.6 fails on the object `handler`.
|
|
101
105
|
::
|
|
102
106
|
|
|
107
|
+
To typecheck the `nuxt` files, install `nuxt@>=4.6` as a `devDependency`. To typecheck `nitro3` files, also install `nitro`.
|
|
108
|
+
|
|
109
|
+
If your module's own aliases already resolve to the right code on both Nitro majors, register the same file for both keys (`{ nitro2: file, nitro3: file }`) or set [`meta.compatibility.server`](#declaring-what-you-cannot-infer).
|
|
110
|
+
|
|
111
|
+
On a `nitropack` v2 host, Nuxt prefers the `nitro2` variant, so the `nuxt` variant only runs there if it is the only one registered. Test the `nuxt` variant on Nuxt 5.
|
|
112
|
+
|
|
113
|
+
In playgrounds and test fixtures on Nuxt 5, h3's auto-imported `defineEventHandler` is not available: import it from `nuxt/server`.
|
|
114
|
+
|
|
115
|
+
### Server Utilities
|
|
116
|
+
|
|
117
|
+
If your module exposes utilities that take the event (through an alias, `addServerImports` or a type template), type the parameter as `RequestEvent` from `nuxt/server`, or as the part it reads, such as `Pick<RequestEvent, 'req' | 'context'>`. A parameter typed as `H3Event` only accepts the event of one h3 major, so the utility can't be called from a `nuxt/server` handler.
|
|
118
|
+
|
|
119
|
+
`getNitroVersion` reports the Nitro major, not which server API the host runs: a host with a different `server.builder` runs none of the Nitro ones.
|
|
120
|
+
|
|
103
121
|
### Server Plugins
|
|
104
122
|
|
|
105
123
|
Server plugins take variants too, although they are specific to Nitro so there is no generic `nuxt` variant to register.
|
|
@@ -172,6 +190,8 @@ export default defineNuxtModule({
|
|
|
172
190
|
|
|
173
191
|
If we can't tell, code will be treated as `nitro2`.
|
|
174
192
|
|
|
193
|
+
Nuxt reads the imports of your module's own files, not of the packages they call. A `nuxt` file that calls a library which imports Nitro internally is accepted, but fails under a builder other than Nitro.
|
|
194
|
+
|
|
175
195
|
### Typing Runtime Config and Events
|
|
176
196
|
|
|
177
197
|
To type runtime config keys your module adds, augment `RuntimeConfig` (or `PublicRuntimeConfig`) from `nuxt/schema`. The keys are then typed in `nuxt`, `nitro2` and `nitro3` files alike.
|
|
@@ -186,9 +206,13 @@ declare module 'nuxt/schema' {
|
|
|
186
206
|
|
|
187
207
|
Builder-specific types, such as `H3Event` for `useRequestEvent()` or the full Nitro config in the `nitro:config` hook, come from the generated `.nuxt/nuxt.d.ts`. Without it, they resolve to builder-agnostic types (`RequestEvent` and a reduced Nitro config). Type utilities that accept an event against `RequestEvent` to support any server builder.
|
|
188
208
|
|
|
209
|
+
### Plugins, Storage and Caching
|
|
210
|
+
|
|
211
|
+
A module built on server plugins, storage or caching has no `nuxt` variant, because `nuxt/server` doesn't cover those areas. Register its files as `nitro2` now, and add a `nitro3` variant when you port them.
|
|
212
|
+
|
|
189
213
|
## Nitro-specific Code
|
|
190
214
|
|
|
191
|
-
`nuxt/server` covers request and response work: handlers, errors, router params, query and body reading and validation, headers, CORS, cookies, sessions, redirects, route rules, runtime config
|
|
215
|
+
`nuxt/server` covers request and response work: handlers, errors, router params, query and body reading and validation, headers, CORS, cookies, sessions, redirects, route rules, runtime config, app config, in-process fetch with `serverFetch()` and runtime hooks with `useServerHooks()`. But Nitro covers a lot more, so if you need any of these areas, you might need to stay on Nitro's own imports inside a `nitro2` or `nitro3` file.
|
|
192
216
|
|
|
193
217
|
Use the specifiers of the version the file is for. A file that imports `nitro/*` is read as Nitro 3 code, so a `nitro2` file must import `h3` and `nitropack/*` instead:
|
|
194
218
|
|
|
@@ -197,11 +221,9 @@ Use the specifiers of the version the file is for. A file that imports `nitro/*`
|
|
|
197
221
|
| Storage: `useStorage()` and its driver configuration | `nitro/storage` | `nitropack/runtime` |
|
|
198
222
|
| Caching: `defineCachedHandler()`, `defineCachedFunction()` | `nitro/cache` | `nitropack/runtime` |
|
|
199
223
|
| Server plugins | `definePlugin()` from `nitro` | `defineNitroPlugin()` from `nitropack/runtime` |
|
|
200
|
-
|
|
|
201
|
-
| App-relative fetch | `serverFetch()` from `nitro` | `useNitroApp().localFetch` from `nitropack/runtime` |
|
|
224
|
+
| Nitro's own runtime hooks, such as `request`, `response` and `error` | `useNitroHooks()` from `nitro/app` | `useNitroApp().hooks` from `nitropack/runtime` |
|
|
202
225
|
| Lazy handlers: `lazyEventHandler()` | `nitro/h3` | `h3` |
|
|
203
|
-
|
|
204
|
-
Tasks are also not supported by `nuxt/server`.
|
|
226
|
+
| Tasks: `defineTask()`, `runTask()` | `nitro/task` | `nitropack/runtime` |
|
|
205
227
|
|
|
206
228
|
::read-more{to="/docs/guide/going-further/server-imports#reaching-past-the-surface"}
|
|
207
229
|
See which h3 helpers work with the portable event, and which need Nitro-specific utilities.
|
|
@@ -214,5 +236,5 @@ These behaviors changed with Nitro v3 and may require further updates in your co
|
|
|
214
236
|
- **Routed middleware no longer runs for subpaths.** `nitropack` v2 mounted middleware with a route so that it ran for that route _and_ everything below it (such as `/path/subpath`), with the route stripped from `event.path`. Nitro v3 matches it exactly, like any other handler. When updating, widen the `route` to `/path/**` if you mean to cover both, and read the full path from `event.path`.
|
|
215
237
|
- **A handler registered with no `route` was global middleware.** Nitro v3 requires a route. If you need middleware, register it with `middleware: true` and an explicit route, even if it is intended to run on every path `/**`.
|
|
216
238
|
- **`beforeResponse` and `afterResponse` are not Nitro v3 hooks.** They will work in the compatibility layer, but you should move to the `response` hook, which receives the built `Response`. Note that (even with the compatibility layer) a hook that replaces `response.body`, or reads it while streaming, is not supported.
|
|
217
|
-
- **`globalThis.$fetch` is not present in Nitro 3.** You can use `event.$fetch` or import `$fetch` from `#imports/server`.
|
|
239
|
+
- **`globalThis.$fetch` is not present in Nitro 3.** For a route of the app, use `serverFetch(event, path)` from `nuxt/server`. You can also use `event.$fetch` or import `$fetch` from `#imports/server`.
|
|
218
240
|
- **`import.meta.url` is no longer the server entry.** Nitro v2 rewrote it to a global pointing at the entry, but Nitro v3 emits the real value. Resolve assets from a path you control instead.
|
|
@@ -34,20 +34,22 @@ This code can run under `@nuxt/nitro-server` and under `@nuxt/vite-server`, and
|
|
|
34
34
|
|---|---|
|
|
35
35
|
| `defineEventHandler` | Define a request handler. |
|
|
36
36
|
| `createError`, `isNuxtError` | Construct and recognise an HTTP error. |
|
|
37
|
-
| `getRequestURL` | The URL of the request. |
|
|
37
|
+
| `getRequestURL`, `getRequestHost`, `getRequestProtocol` | The URL, host and protocol of the request. Pass `{ xForwardedHost: true, xForwardedProto: true }` to trust those headers, only behind a proxy you control that overwrites them. |
|
|
38
38
|
| `getRequestHeader`, `getRequestHeaders` | Read request headers. |
|
|
39
39
|
| `getRouterParam`, `getRouterParams` | Read the dynamic segments matched for the request. |
|
|
40
40
|
| `getRequestIP` | The client IP address, with [forwarded headers trusted on request](#client-ip). |
|
|
41
41
|
| `getQuery`, `getValidatedQuery` | Read the query string, optionally [validated](#validation). |
|
|
42
42
|
| `readBody`, `readValidatedBody` | Read and parse the request body, optionally [validated](#validation). |
|
|
43
|
-
| `getCookie`, `setCookie`, `deleteCookie` | Read and write cookies. |
|
|
43
|
+
| `getCookie`, `parseCookies`, `setCookie`, `deleteCookie` | Read one or every cookie, and write cookies. |
|
|
44
44
|
| `setResponseStatus` | Set the response status and reason phrase. |
|
|
45
45
|
| `handleCors` | Apply [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers and answer preflight requests. |
|
|
46
46
|
| `sendRedirect` | Redirect the request. |
|
|
47
|
+
| `serverFetch` | Fetch a route of the app in-process, with the path relative to `app.baseURL` and the `cookie` and `authorization` headers forwarded unless `forwardHeaders` is set. It rejects on a server builder without an in-process fetch. |
|
|
47
48
|
| `useSession`, `getSession`, `updateSession`, `clearSession` | Read and write a [sealed session cookie](#sessions). |
|
|
48
49
|
| `deriveSecret` | A purpose-specific secret [derived from `appSecret`](#deriving-secrets). |
|
|
49
|
-
| `getRouteRules` | The [route rules](/docs/guide/concepts/rendering#route-rules) matched for the request. |
|
|
50
|
+
| `getRouteRules`, `matchRouteRules` | The [route rules](/docs/guide/concepts/rendering#route-rules) matched for the request, or for another path. |
|
|
50
51
|
| `useRuntimeConfig` | The server's [runtime configuration](/docs/guide/going-further/runtime-config). |
|
|
52
|
+
| `useServerHooks` | The server's runtime hooks: renderer hooks such as `render:html`, and those declared on `NuxtServerHooks`. |
|
|
51
53
|
| `useAppConfig` | The [app config](/docs/directory-structure/app/app-config), as a copy per request when passed the event. |
|
|
52
54
|
|
|
53
55
|
Types are exported alongside the utilities: `RequestEvent`, `RequestEventContext`, `NuxtRequestEvent`, `EventHandler`, `AppRouteRules`, `ServerRoutes`, `CorsOptions`, `ValidateResult`, `NuxtError`, `NuxtErrorDetails`, `NuxtErrorJSON`, `NuxtErrorLike`, `Session`, `SessionConfig`, `SessionData`, `SessionEvent`, `SessionManager`, `SessionPassword` and `SessionUpdate`.
|
|
@@ -84,6 +86,16 @@ export default defineEventHandler(async (event) => {
|
|
|
84
86
|
|
|
85
87
|
`NuxtRequestEvent` is the same request in the shape the configured builder provides, which is h3's `H3Event` under `@nuxt/nitro-server`.
|
|
86
88
|
|
|
89
|
+
## Handlers
|
|
90
|
+
|
|
91
|
+
A handler file must default-export the result of `defineEventHandler` from `nuxt/server`. A bare function, or one wrapped by h3's `defineEventHandler`, receives the server runtime's own event instead.
|
|
92
|
+
|
|
93
|
+
A handler may return:
|
|
94
|
+
|
|
95
|
+
- A JSON-serializable value, sent as JSON with the status and headers set on `event.res`.
|
|
96
|
+
- A `Response`, sent with its own status. Headers set on `event.res.headers` are added to it, replacing a header of the same name, apart from `set-cookie`, which is appended.
|
|
97
|
+
- A `ReadableStream`, streamed as the body.
|
|
98
|
+
|
|
87
99
|
## Validation
|
|
88
100
|
|
|
89
101
|
`readValidatedBody` and `getValidatedQuery` take any [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType and others), or a function that returns the validated value, `true` to accept the input or `false` to reject it.
|
|
@@ -150,7 +162,7 @@ The session travels in the cookie, so it is limited to what a browser will accep
|
|
|
150
162
|
|
|
151
163
|
## Reaching Past the Surface
|
|
152
164
|
|
|
153
|
-
`nuxt/server` isn't a re-export of h3, so if you need something else that h3 and Nitro offer, such as the server lifecycle (`definePlugin
|
|
165
|
+
`nuxt/server` isn't a re-export of h3, so if you need something else that h3 and Nitro offer, such as the server lifecycle (`definePlugin` and `defineErrorHandler`) or Nitro's own runtime hooks, you would import it directly.
|
|
154
166
|
|
|
155
167
|
Most of those helpers take the event as it is:
|
|
156
168
|
|
|
@@ -174,7 +186,9 @@ import { defineEventHandler, proxyRequest } from 'nitro/h3'
|
|
|
174
186
|
export default defineEventHandler(event => proxyRequest(event, 'https://example.com'))
|
|
175
187
|
```
|
|
176
188
|
|
|
177
|
-
|
|
189
|
+
A file may import from both `nitro/*` and `nuxt/server`. It then runs only on Nitro v3, so a module registers it as its `nitro3` variant.
|
|
190
|
+
|
|
191
|
+
Nitro's own APIs mostly take no event at all: `getRouteRules(method, pathname)`, `defineCachedHandler()`, `useStorage()`, `useDatabase()` and tasks.
|
|
178
192
|
|
|
179
193
|
## What Isn't Portable
|
|
180
194
|
|
|
@@ -182,9 +196,9 @@ These areas mean reaching outside `nuxt/server`, because Nuxt can't provide them
|
|
|
182
196
|
|
|
183
197
|
- **Storage.** `useStorage()` comes from `nitro/storage`, and so does the driver configuration behind it.
|
|
184
198
|
- **Caching.** `defineCachedHandler()` and `defineCachedFunction()` come from `nitro/cache`. For caching that runs anywhere, depend on a cache library directly.
|
|
185
|
-
- **Server plugins
|
|
186
|
-
- **App-relative fetch.** `serverFetch()` comes from `nitro`. It calls a route of the app without an origin, which needs the runtime's router.
|
|
199
|
+
- **Server plugins.** `definePlugin()` comes from `nitro`. Inside a plugin, `useServerHooks()` from `nuxt/server` registers the renderer hooks (including `render:html`) and those declared on `NuxtServerHooks`; Nitro's own hooks, such as `request`, `response` and `error`, come from `useNitroHooks()` in `nitro/app`.
|
|
187
200
|
- **Lazy handlers.** `lazyEventHandler()` comes from `nitro/h3`.
|
|
201
|
+
- **Tasks.** `defineTask()` and `runTask()` come from `nitro/task`.
|
|
188
202
|
|
|
189
203
|
## Server Code Only
|
|
190
204
|
|
|
@@ -61,7 +61,7 @@ Most of the options will be directly passed to the [cookie](https://github.com/j
|
|
|
61
61
|
| `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. |
|
|
62
62
|
| `default` | `() => T \| Ref<T>` | `undefined` | Function returning the default value if the cookie does not exist. The function can also return a `Ref`. |
|
|
63
63
|
| `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). |
|
|
64
|
-
| `refresh` :badge[v4.4]{color="info" size="xs" class="align-middle"} | `boolean` | `false` | If `true`, the cookie expiration will be refreshed on every explicit write (e.g. `cookie.value = cookie.value`), even if the value itself hasn’t changed. Note: the expiration is not refreshed automatically
|
|
64
|
+
| `refresh` :badge[v4.4]{color="info" size="xs" class="align-middle"} | `boolean` | `false` | If `true`, the cookie expiration will be refreshed on every explicit write (e.g. `cookie.value = cookie.value`), even if the value itself hasn’t changed. Note: the expiration is not refreshed automatically; you must assign to `.value` to trigger it. |
|
|
65
65
|
| `readonly` | `boolean` | `false` | If `true`, disables writing to the cookie, on both server and client. A `default` value is still returned by the composable but is never persisted to the browser. |
|
|
66
66
|
| `maxAge` | `number` | `undefined` | Max age in seconds for the cookie, i.e. the value for the [`Max-Age` `Set-Cookie` attribute](https://datatracker.ietf.org/doc/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. |
|
|
67
67
|
| `expires` | `Date \| (() => Date \| undefined)` | `undefined` | Expiration date for the cookie, or a getter that returns one. When a function is provided, it is evaluated on every cookie write, so the expiration can be refreshed when the value is re-set. Returning `undefined` creates a session cookie. The getter should be pure (no side effects). 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://datatracker.ietf.org/doc/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. |
|
|
@@ -194,7 +194,7 @@ Use a function for `expires` when you want a fresh expiration date every time th
|
|
|
194
194
|
```vue [app/app.vue]
|
|
195
195
|
<script setup lang="ts">
|
|
196
196
|
const token = useCookie('token', {
|
|
197
|
-
// Re-evaluated on every write
|
|
197
|
+
// Re-evaluated on every write: keep this getter pure
|
|
198
198
|
expires: () => new Date(Date.now() + 60 * 60 * 1000), // 1 hour from now
|
|
199
199
|
})
|
|
200
200
|
|