@nuxt/docs 4.0.0-alpha.2 → 4.0.0-alpha.3

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
 
@@ -135,7 +135,7 @@ export default defineNuxtConfig({
135
135
  });
136
136
  ```
137
137
 
138
- ## Runtime prerender configuration
138
+ ## Runtime Prerender Configuration
139
139
 
140
140
  ### `prerenderRoutes`
141
141
 
@@ -444,7 +444,7 @@ If you prefer to use `@vue/test-utils` on its own for unit testing in Nuxt, and
444
444
 
445
445
  2. Create a `vitest.config.ts` with the following content:
446
446
 
447
- ```ts twoslash
447
+ ```ts
448
448
  import { defineConfig } from 'vitest/config'
449
449
  import vue from '@vitejs/plugin-vue'
450
450
 
@@ -980,6 +980,93 @@ const importName = genSafeVariableName
980
980
  You can automate this step by running `npx codemod@latest nuxt/4/template-compilation-changes`
981
981
  ::
982
982
 
983
+ ### TypeScript Configuration Changes
984
+
985
+ 🚦 **Impact Level**: Minimal
986
+
987
+ #### What Changed
988
+
989
+ Nuxt now generates separate TypeScript configurations for different contexts to provide better type-checking experiences:
990
+
991
+ 1. **New TypeScript configuration files**: Nuxt now generates additional TypeScript configurations:
992
+ * `.nuxt/tsconfig.app.json` - For your app code (Vue components, composables, etc.)
993
+ * `.nuxt/tsconfig.server.json` - For your server-side code (Nitro/server directory)
994
+ * `.nuxt/tsconfig.node.json` - For your build-time code (modules, `nuxt.config.ts`, etc.)
995
+ * `.nuxt/tsconfig.json` - Legacy configuration for backward compatibility
996
+
997
+ 2. **Backward compatibility**: Existing projects that extend `.nuxt/tsconfig.json` will continue to work as before.
998
+
999
+ 3. **Opt-in project references**: New projects or those wanting better type checking can adopt TypeScript's project references feature.
1000
+
1001
+ 4. **Context-specific type checking**: Each context now has appropriate compiler options and includes/excludes for its specific environment.
1002
+
1003
+ 5. **New `typescript.nodeTsConfig` option**: You can now customize the TypeScript configuration for Node.js build-time code.
1004
+
1005
+ #### Reasons for Change
1006
+
1007
+ This change provides several benefits:
1008
+
1009
+ 1. **Better type safety**: Each context (app, server, build-time) gets appropriate type checking with context-specific globals and APIs.
1010
+ 2. **Improved IDE experience**: Better IntelliSense and error reporting for different parts of your codebase.
1011
+ 3. **Cleaner separation**: Server code won't incorrectly suggest client-side APIs and vice versa.
1012
+ 4. **Performance**: TypeScript can more efficiently check code with properly scoped configurations.
1013
+
1014
+ For example, auto-imports are not available in your `nuxt.config.ts` (but previously this was not flagged by TypeScript). And while IDEs recognized the separate context hinted by `tsconfig.json` in your `server/` directory, this was not reflected in type-checking (requiring a separate step).
1015
+
1016
+ #### Migration Steps
1017
+
1018
+ **No migration is required** - existing projects will continue to work as before.
1019
+
1020
+ However, to take advantage of improved type checking, you can opt in to the new project references approach:
1021
+
1022
+ 1. **Update your root `tsconfig.json`** to use project references:
1023
+
1024
+ ```json
1025
+ {
1026
+ "files": [],
1027
+ "references": [
1028
+ { "path": "./.nuxt/tsconfig.app.json" },
1029
+ { "path": "./.nuxt/tsconfig.server.json" },
1030
+ { "path": "./.nuxt/tsconfig.node.json" }
1031
+ ]
1032
+ }
1033
+ ```
1034
+
1035
+ 2. **Remove any manual server `tsconfig.json`** files (like `server/tsconfig.json`) that extended `.nuxt/tsconfig.server.json`.
1036
+
1037
+ 3. **Update your type checking scripts** to use the build flag for project references:
1038
+
1039
+ ```diff
1040
+ - "typecheck": "nuxt prepare && vue-tsc --noEmit"
1041
+ + "typecheck": "nuxt prepare && vue-tsc -b --noEmit"
1042
+ ```
1043
+
1044
+ 4. **Configure Node.js TypeScript options** if needed:
1045
+ <!-- @case-police-ignore tsConfig -->
1046
+
1047
+ ```ts
1048
+ export default defineNuxtConfig({
1049
+ typescript: {
1050
+ // Customize app/server TypeScript config
1051
+ tsConfig: {
1052
+ compilerOptions: {
1053
+ strict: true
1054
+ }
1055
+ },
1056
+ // Customize build-time TypeScript config
1057
+ nodeTsConfig: {
1058
+ compilerOptions: {
1059
+ strict: true
1060
+ }
1061
+ }
1062
+ }
1063
+ })
1064
+ ```
1065
+
1066
+ 5. **Update any CI/build scripts** that run TypeScript checking to ensure they use the new project references approach.
1067
+
1068
+ The new configuration provides better type safety and IntelliSense for projects that opt in, while maintaining full backward compatibility for existing setups.
1069
+
983
1070
  ### Removal of Experimental Features
984
1071
 
985
1072
  🚦 **Impact Level**: Minimal
@@ -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.
@@ -55,7 +55,7 @@ This file contains the types of any modules you are using, as well as the key ty
55
55
 
56
56
  Some of the references in the file are to files that are only generated within your `buildDir` (`.nuxt`) and therefore for full typings, you will need to run `nuxt dev` or `nuxt build`.
57
57
 
58
- ### `.nuxt/tsconfig.json`
58
+ ### `.nuxt/tsconfig.app.json`
59
59
 
60
60
  This file contains the recommended basic TypeScript configuration for your project, including resolved aliases injected by Nuxt or modules you are using, so you can get full type support and path auto-complete for aliases like `~/file` or `#build/file`.
61
61
 
@@ -74,10 +74,37 @@ Nitro also [auto-generates types](/docs/guide/concepts/server-engine#typed-api-r
74
74
  ::
75
75
 
76
76
  ::note
77
- Keep in mind that all options extended from `./.nuxt/tsconfig.json` will be overwritten by the options defined in your `tsconfig.json`.
78
- Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead TypeScript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#imports` not being recognized.
79
- :br :br
80
- In case you need to extend options provided by `./.nuxt/tsconfig.json` further, you can use the [`alias` property](/docs/api/nuxt-config#alias) within your `nuxt.config`. Nuxt will pick them up and extend `./.nuxt/tsconfig.json` accordingly.
77
+ For backward compatibility, Nuxt still generates `./.nuxt/tsconfig.json`. However, we recommend using [TypeScript project references](/docs/guide/directory-structure/tsconfig) with the new configuration files (`.nuxt/tsconfig.app.json`, `.nuxt/tsconfig.server.json`, etc.) for better type safety and performance.
78
+
79
+ If you do extend from `./.nuxt/tsconfig.json`, keep in mind that all options will be overwritten by those defined in your `tsconfig.json`. Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead TypeScript to not factor in the module resolutions, which can cause module resolutions such as `#imports` to not be recognized.
80
+
81
+ In case you need to extend options further, you can use the [`alias` property](/docs/api/nuxt-config#alias) within your `nuxt.config`. Nuxt will pick them up and extend the generated TypeScript configurations accordingly.
82
+ ::
83
+
84
+ ## Project References
85
+
86
+ Nuxt uses [TypeScript project references](https://www.typescriptlang.org/docs/handbook/project-references.html) to improve type-checking performance and provide better IDE support. This feature allows TypeScript to break up your codebase into smaller, more manageable pieces.
87
+
88
+ ### How Nuxt Uses Project References
89
+
90
+ When you run `nuxt dev` or `nuxt build`, Nuxt will generate multiple `tsconfig.json` files for different parts of your application.
91
+
92
+ - **`.nuxt/tsconfig.app.json`** - Configuration for your application code
93
+ - **`.nuxt/tsconfig.node.json`** - Configuration for your `nuxt.config` and modules
94
+ - **`.nuxt/tsconfig.server.json`** - Configuration for server-side code (when applicable)
95
+ - **`.nuxt/tsconfig.json`** - Legacy configuration for backward compatibility
96
+
97
+ Each of these files is configured to reference the appropriate dependencies and provide optimal type-checking for their specific context.
98
+
99
+ ### Benefits of Project References
100
+
101
+ - **Faster builds**: TypeScript can skip rebuilding unchanged projects
102
+ - **Better IDE performance**: Your IDE can provide faster IntelliSense and error checking
103
+ - **Isolated compilation**: Errors in one part of your application don't prevent compilation of other parts
104
+ - **Clearer dependency management**: Each project explicitly declares its dependencies
105
+
106
+ ::note
107
+ The project reference setup is handled automatically by Nuxt. You typically don't need to modify these configurations manually, but understanding how they work can help you troubleshoot type-checking issues.
81
108
  ::
82
109
 
83
110
  ## Strict Checks
@@ -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
 
@@ -136,16 +136,6 @@ export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D> (
136
136
  This feature is available from Nuxt >= 3.5
137
137
  ::
138
138
 
139
- To improve clarity within your IDE between the auto-imports from 'nitro' and 'vue', you can add a `~/server/tsconfig.json` with the following content:
140
-
141
- ```json [server/tsconfig.json]
142
- {
143
- "extends": "../.nuxt/tsconfig.server.json"
144
- }
145
- ```
146
-
147
- Currently, these values won't be respected when type checking ([`nuxt typecheck`](/docs/api/commands/typecheck)), but you should get better type hints in your IDE.
148
-
149
139
  ## Recipes
150
140
 
151
141
  ### Route Parameters
@@ -448,7 +438,7 @@ export default fromNodeMiddleware((req, res) => {
448
438
  ```
449
439
 
450
440
  ::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.
441
+ 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
442
  ::
453
443
 
454
444
  ```ts [server/middleware/legacy.ts]
@@ -1,17 +1,28 @@
1
1
  ---
2
2
  title: "tsconfig.json"
3
- description: "Nuxt generates a .nuxt/tsconfig.json file with sensible defaults and your aliases."
3
+ description: "Nuxt generates multiple TypeScript configuration files with sensible defaults and your aliases."
4
4
  head.title: "tsconfig.json"
5
5
  navigation.icon: i-lucide-file
6
6
  ---
7
7
 
8
- Nuxt [automatically generates](/docs/guide/concepts/typescript) a `.nuxt/tsconfig.json` file with the resolved aliases you are using in your Nuxt project, as well as with other sensible defaults.
8
+ Nuxt [automatically generates](/docs/guide/concepts/typescript) multiple TypeScript configuration files (`.nuxt/tsconfig.app.json`, `.nuxt/tsconfig.server.json`, `.nuxt/tsconfig.node.json`) with the resolved aliases you are using in your Nuxt project, as well as with other sensible defaults.
9
9
 
10
10
  You can benefit from this by creating a `tsconfig.json` in the root of your project with the following content:
11
11
 
12
12
  ```json [tsconfig.json]
13
13
  {
14
- "extends": "./.nuxt/tsconfig.json"
14
+ "files": [],
15
+ "references": [
16
+ {
17
+ "path": "./.nuxt/tsconfig.app.json"
18
+ },
19
+ {
20
+ "path": "./.nuxt/tsconfig.server.json"
21
+ },
22
+ {
23
+ "path": "./.nuxt/tsconfig.node.json"
24
+ }
25
+ ]
15
26
  }
16
27
  ```
17
28
 
@@ -386,6 +386,7 @@ package-lock.json
386
386
  yarn.lock
387
387
  pnpm-lock.yaml
388
388
  tsconfig.json
389
+ bun.lock
389
390
  bun.lockb
390
391
  ```
391
392
 
@@ -32,7 +32,7 @@ Update `nuxt` dependency inside `package.json`:
32
32
  }
33
33
  ```
34
34
 
35
- Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
35
+ Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock` or `bun.lockb`) and reinstall dependencies.
36
36
 
37
37
  ## Opting Out
38
38
 
@@ -47,7 +47,7 @@ Update `nuxt` dependency inside `package.json`:
47
47
  }
48
48
  ```
49
49
 
50
- Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
50
+ Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock` or `bun.lockb`) and reinstall dependencies.
51
51
 
52
52
  ## Using Nightly `@nuxt/cli`
53
53
 
@@ -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
+ ```
@@ -36,7 +36,7 @@ function useLogger (tag?: string, options?: Partial<ConsolaOptions>): ConsolaIns
36
36
 
37
37
  ### Parameters
38
38
 
39
- **`tag`**: A tag to suffix all log messages with.
39
+ **`tag`**: A tag to suffix all log messages with, displayed on the right near the timestamp.
40
40
 
41
41
  **`options`**: Consola configuration options.
42
42
 
@@ -128,7 +128,7 @@ The Nuxt instance as described in the `useNuxt` section.
128
128
  ::code-group
129
129
 
130
130
  ```ts twoslash [requireSiteConfig.ts]
131
- declare module '@nuxt/schema' {
131
+ declare module 'nuxt/schema' {
132
132
  interface NuxtOptions {
133
133
  siteConfig: SiteConfig
134
134
  }
@@ -68,7 +68,7 @@ Hook | Arguments | Description
68
68
  `nitro:build:public-assets` | `nitro` | Called after copying public assets. Allows modifying public assets before Nitro server is built.
69
69
  `prerender:routes` | `ctx` | Allows extending the routes to be pre-rendered.
70
70
  `build:error` | `error` | Called when an error occurs at build time.
71
- `prepare:types` | `options` | Called before `@nuxt/cli` writes `.nuxt/tsconfig.json` and `.nuxt/nuxt.d.ts`, allowing addition of custom references and declarations in `nuxt.d.ts`, or directly modifying the options in `tsconfig.json`
71
+ `prepare:types` | `options` | Called before `@nuxt/cli` writes TypeScript configuration files (`.nuxt/tsconfig.app.json`, `.nuxt/tsconfig.server.json`, etc.) and `.nuxt/nuxt.d.ts`, allowing addition of custom references and declarations in `nuxt.d.ts`, or directly modifying the options in generated configurations
72
72
  `listen` | `listenerServer, listener` | Called when the dev server is loading.
73
73
  `schema:extend` | `schemas` | Allows extending default schemas.
74
74
  `schema:resolved` | `schema` | Allows extending resolved schema.
@@ -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
@@ -31,9 +31,8 @@ your alias by prefixing it with `~`.
31
31
  ::
32
32
 
33
33
  ::callout
34
- **Note**: These aliases will be automatically added to the generated `.nuxt/tsconfig.json` so you can get full
35
- type support and path auto-complete. In case you need to extend options provided by `./.nuxt/tsconfig.json`
36
- further, make sure to add them here or within the `typescript.TSConfig` property in `nuxt.config`.
34
+ <!-- @case-police-ignore tsConfig -->
35
+ **Note**: These aliases will be automatically added to the generated TypeScript configurations (`.nuxt/tsconfig.app.json`, `.nuxt/tsconfig.server.json`, etc.) so you can get full type support and path auto-complete. In case you need to extend options provided by the generated configurations further, make sure to add them here or within the `typescript.tsConfig` property in `nuxt.config`.
37
36
  ::
38
37
 
39
38
  **Example**:
@@ -2058,9 +2057,11 @@ TypeScript comes with certain checks to give you more safety and analysis of you
2058
2057
  - **Type**: `boolean`
2059
2058
  - **Default:** `true`
2060
2059
 
2061
- ### `TSConfig`
2060
+ <!-- @case-police-ignore tsConfig -->
2062
2061
 
2063
- You can extend generated `.nuxt/tsconfig.json` using this option.
2062
+ ### `tsConfig`
2063
+
2064
+ You can extend the generated TypeScript configurations (`.nuxt/tsconfig.app.json`, `.nuxt/tsconfig.server.json`, etc.) using this option.
2064
2065
 
2065
2066
  ### `typeCheck`
2066
2067
 
@@ -36,6 +36,8 @@ If you are using TypeScript, you can edit your `tsconfig.json` to benefit from a
36
36
 
37
37
  ::note
38
38
  As `.nuxt/tsconfig.json` is generated and not checked into version control, you'll need to generate that file before running your tests. Add `nuxi prepare` as a step before your tests, otherwise you'll see `TS5083: Cannot read file '~/.nuxt/tsconfig.json'`
39
+
40
+ For modern Nuxt projects, we recommend using [TypeScript project references](/docs/guide/directory-structure/tsconfig) instead of directly extending `.nuxt/tsconfig.json`.
39
41
  ::
40
42
 
41
43
  ::note
@@ -156,11 +156,22 @@ Nuxt can type-check your app using [`vue-tsc`](https://github.com/vuejs/language
156
156
 
157
157
  ```json
158
158
  {
159
- "extends": "./.nuxt/tsconfig.json"
159
+ "files": [],
160
+ "references": [
161
+ {
162
+ "path": "./.nuxt/tsconfig.app.json"
163
+ },
164
+ {
165
+ "path": "./.nuxt/tsconfig.server.json"
166
+ },
167
+ {
168
+ "path": "./.nuxt/tsconfig.node.json"
169
+ }
170
+ ]
160
171
  }
161
172
  ```
162
173
 
163
- 1. Run `npx nuxt prepare` to generate `.nuxt/tsconfig.json`.
174
+ 1. Run `npx nuxt prepare` to generate the tsconfig files.
164
175
  1. Install Volar following the instructions in the [docs](/docs/getting-started/introduction#prerequisites).
165
176
 
166
177
  ## Vue Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs",
3
- "version": "4.0.0-alpha.2",
3
+ "version": "4.0.0-alpha.3",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",