@nuxt/docs 0.0.0 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/.navigation.yml +2 -0
  2. package/1.getting-started/.navigation.yml +3 -0
  3. package/1.getting-started/01.introduction.md +81 -0
  4. package/1.getting-started/02.installation.md +109 -0
  5. package/1.getting-started/03.configuration.md +226 -0
  6. package/1.getting-started/04.views.md +163 -0
  7. package/1.getting-started/05.assets.md +48 -0
  8. package/1.getting-started/06.styling.md +565 -0
  9. package/1.getting-started/07.routing.md +149 -0
  10. package/1.getting-started/08.seo-meta.md +360 -0
  11. package/1.getting-started/09.transitions.md +473 -0
  12. package/1.getting-started/10.data-fetching.md +795 -0
  13. package/1.getting-started/11.state-management.md +223 -0
  14. package/1.getting-started/12.error-handling.md +233 -0
  15. package/1.getting-started/13.server.md +94 -0
  16. package/1.getting-started/14.layers.md +92 -0
  17. package/1.getting-started/15.prerendering.md +194 -0
  18. package/1.getting-started/16.deployment.md +130 -0
  19. package/1.getting-started/17.testing.md +728 -0
  20. package/1.getting-started/18.upgrade.md +997 -0
  21. package/2.guide/.navigation.yml +2 -0
  22. package/2.guide/0.index.md +22 -0
  23. package/2.guide/1.concepts/.navigation.yml +3 -0
  24. package/2.guide/1.concepts/1.auto-imports.md +205 -0
  25. package/2.guide/1.concepts/10.nuxt-lifecycle.md +141 -0
  26. package/2.guide/1.concepts/2.vuejs-development.md +103 -0
  27. package/2.guide/1.concepts/3.rendering.md +255 -0
  28. package/2.guide/1.concepts/4.server-engine.md +62 -0
  29. package/2.guide/1.concepts/5.modules.md +48 -0
  30. package/2.guide/1.concepts/7.esm.md +299 -0
  31. package/2.guide/1.concepts/8.typescript.md +97 -0
  32. package/2.guide/1.concepts/9.code-style.md +22 -0
  33. package/2.guide/2.directory-structure/.navigation.yml +3 -0
  34. package/2.guide/2.directory-structure/0.nuxt.md +20 -0
  35. package/2.guide/2.directory-structure/0.output.md +18 -0
  36. package/2.guide/2.directory-structure/1.assets.md +16 -0
  37. package/2.guide/2.directory-structure/1.components.md +608 -0
  38. package/2.guide/2.directory-structure/1.composables.md +121 -0
  39. package/2.guide/2.directory-structure/1.content.md +64 -0
  40. package/2.guide/2.directory-structure/1.layouts.md +180 -0
  41. package/2.guide/2.directory-structure/1.middleware.md +209 -0
  42. package/2.guide/2.directory-structure/1.modules.md +66 -0
  43. package/2.guide/2.directory-structure/1.node_modules.md +12 -0
  44. package/2.guide/2.directory-structure/1.pages.md +440 -0
  45. package/2.guide/2.directory-structure/1.plugins.md +299 -0
  46. package/2.guide/2.directory-structure/1.public.md +27 -0
  47. package/2.guide/2.directory-structure/1.server.md +546 -0
  48. package/2.guide/2.directory-structure/1.shared.md +104 -0
  49. package/2.guide/2.directory-structure/1.utils.md +49 -0
  50. package/2.guide/2.directory-structure/2.env.md +75 -0
  51. package/2.guide/2.directory-structure/2.gitignore.md +37 -0
  52. package/2.guide/2.directory-structure/2.nuxtignore.md +36 -0
  53. package/2.guide/2.directory-structure/2.nuxtrc.md +50 -0
  54. package/2.guide/2.directory-structure/3.app-config.md +177 -0
  55. package/2.guide/2.directory-structure/3.app.md +72 -0
  56. package/2.guide/2.directory-structure/3.error.md +55 -0
  57. package/2.guide/2.directory-structure/3.nuxt-config.md +34 -0
  58. package/2.guide/2.directory-structure/3.package.md +32 -0
  59. package/2.guide/2.directory-structure/3.tsconfig.md +24 -0
  60. package/2.guide/3.going-further/.navigation.yml +3 -0
  61. package/2.guide/3.going-further/1.experimental-features.md +689 -0
  62. package/2.guide/3.going-further/1.features.md +103 -0
  63. package/2.guide/3.going-further/1.internals.md +81 -0
  64. package/2.guide/3.going-further/10.runtime-config.md +174 -0
  65. package/2.guide/3.going-further/11.nightly-release-channel.md +68 -0
  66. package/2.guide/3.going-further/2.hooks.md +98 -0
  67. package/2.guide/3.going-further/3.modules.md +811 -0
  68. package/2.guide/3.going-further/4.kit.md +51 -0
  69. package/2.guide/3.going-further/6.nuxt-app.md +64 -0
  70. package/2.guide/3.going-further/7.layers.md +227 -0
  71. package/2.guide/3.going-further/9.debugging.md +115 -0
  72. package/2.guide/3.going-further/index.md +4 -0
  73. package/2.guide/4.recipes/.navigation.yml +3 -0
  74. package/2.guide/4.recipes/1.custom-routing.md +181 -0
  75. package/2.guide/4.recipes/2.vite-plugin.md +65 -0
  76. package/2.guide/4.recipes/3.custom-usefetch.md +125 -0
  77. package/2.guide/4.recipes/4.sessions-and-authentication.md +203 -0
  78. package/3.api/.navigation.yml +3 -0
  79. package/3.api/1.components/.navigation.yml +3 -0
  80. package/3.api/1.components/1.client-only.md +76 -0
  81. package/3.api/1.components/1.dev-only.md +51 -0
  82. package/3.api/1.components/1.nuxt-client-fallback.md +80 -0
  83. package/3.api/1.components/10.nuxt-picture.md +27 -0
  84. package/3.api/1.components/11.teleports.md +40 -0
  85. package/3.api/1.components/12.nuxt-route-announcer.md +56 -0
  86. package/3.api/1.components/13.nuxt-time.md +173 -0
  87. package/3.api/1.components/2.nuxt-page.md +154 -0
  88. package/3.api/1.components/3.nuxt-layout.md +156 -0
  89. package/3.api/1.components/4.nuxt-link.md +322 -0
  90. package/3.api/1.components/5.nuxt-loading-indicator.md +50 -0
  91. package/3.api/1.components/6.nuxt-error-boundary.md +65 -0
  92. package/3.api/1.components/7.nuxt-welcome.md +25 -0
  93. package/3.api/1.components/8.nuxt-island.md +70 -0
  94. package/3.api/1.components/9.nuxt-img.md +43 -0
  95. package/3.api/2.composables/.navigation.yml +3 -0
  96. package/3.api/2.composables/on-prehydrate.md +60 -0
  97. package/3.api/2.composables/use-app-config.md +19 -0
  98. package/3.api/2.composables/use-async-data.md +212 -0
  99. package/3.api/2.composables/use-cookie.md +233 -0
  100. package/3.api/2.composables/use-error.md +32 -0
  101. package/3.api/2.composables/use-fetch.md +217 -0
  102. package/3.api/2.composables/use-head-safe.md +55 -0
  103. package/3.api/2.composables/use-head.md +69 -0
  104. package/3.api/2.composables/use-hydration.md +68 -0
  105. package/3.api/2.composables/use-lazy-async-data.md +47 -0
  106. package/3.api/2.composables/use-lazy-fetch.md +55 -0
  107. package/3.api/2.composables/use-loading-indicator.md +77 -0
  108. package/3.api/2.composables/use-nuxt-app.md +294 -0
  109. package/3.api/2.composables/use-nuxt-data.md +112 -0
  110. package/3.api/2.composables/use-preview-mode.md +118 -0
  111. package/3.api/2.composables/use-request-event.md +23 -0
  112. package/3.api/2.composables/use-request-fetch.md +52 -0
  113. package/3.api/2.composables/use-request-header.md +34 -0
  114. package/3.api/2.composables/use-request-headers.md +37 -0
  115. package/3.api/2.composables/use-request-url.md +41 -0
  116. package/3.api/2.composables/use-response-header.md +48 -0
  117. package/3.api/2.composables/use-route-announcer.md +60 -0
  118. package/3.api/2.composables/use-route.md +52 -0
  119. package/3.api/2.composables/use-router.md +92 -0
  120. package/3.api/2.composables/use-runtime-config.md +142 -0
  121. package/3.api/2.composables/use-runtime-hook.md +43 -0
  122. package/3.api/2.composables/use-seo-meta.md +80 -0
  123. package/3.api/2.composables/use-server-seo-meta.md +27 -0
  124. package/3.api/2.composables/use-state.md +48 -0
  125. package/3.api/3.utils/$fetch.md +98 -0
  126. package/3.api/3.utils/.navigation.yml +3 -0
  127. package/3.api/3.utils/abort-navigation.md +73 -0
  128. package/3.api/3.utils/add-route-middleware.md +88 -0
  129. package/3.api/3.utils/call-once.md +92 -0
  130. package/3.api/3.utils/clear-error.md +29 -0
  131. package/3.api/3.utils/clear-nuxt-data.md +23 -0
  132. package/3.api/3.utils/clear-nuxt-state.md +23 -0
  133. package/3.api/3.utils/create-error.md +55 -0
  134. package/3.api/3.utils/define-nuxt-component.md +53 -0
  135. package/3.api/3.utils/define-nuxt-route-middleware.md +67 -0
  136. package/3.api/3.utils/define-page-meta.md +234 -0
  137. package/3.api/3.utils/define-route-rules.md +52 -0
  138. package/3.api/3.utils/navigate-to.md +230 -0
  139. package/3.api/3.utils/on-before-route-leave.md +11 -0
  140. package/3.api/3.utils/on-before-route-update.md +11 -0
  141. package/3.api/3.utils/on-nuxt-ready.md +25 -0
  142. package/3.api/3.utils/prefetch-components.md +28 -0
  143. package/3.api/3.utils/preload-components.md +23 -0
  144. package/3.api/3.utils/preload-route-components.md +41 -0
  145. package/3.api/3.utils/prerender-routes.md +46 -0
  146. package/3.api/3.utils/refresh-cookie.md +46 -0
  147. package/3.api/3.utils/refresh-nuxt-data.md +91 -0
  148. package/3.api/3.utils/reload-nuxt-app.md +74 -0
  149. package/3.api/3.utils/set-page-layout.md +24 -0
  150. package/3.api/3.utils/set-response-status.md +36 -0
  151. package/3.api/3.utils/show-error.md +31 -0
  152. package/3.api/3.utils/update-app-config.md +27 -0
  153. package/3.api/4.commands/.navigation.yml +3 -0
  154. package/3.api/4.commands/add.md +112 -0
  155. package/3.api/4.commands/analyze.md +41 -0
  156. package/3.api/4.commands/build-module.md +42 -0
  157. package/3.api/4.commands/build.md +46 -0
  158. package/3.api/4.commands/cleanup.md +38 -0
  159. package/3.api/4.commands/dev.md +59 -0
  160. package/3.api/4.commands/devtools.md +38 -0
  161. package/3.api/4.commands/generate.md +41 -0
  162. package/3.api/4.commands/info.md +33 -0
  163. package/3.api/4.commands/init.md +46 -0
  164. package/3.api/4.commands/module.md +84 -0
  165. package/3.api/4.commands/prepare.md +36 -0
  166. package/3.api/4.commands/preview.md +43 -0
  167. package/3.api/4.commands/typecheck.md +42 -0
  168. package/3.api/4.commands/upgrade.md +37 -0
  169. package/3.api/5.kit/.navigation.yml +3 -0
  170. package/3.api/5.kit/1.modules.md +172 -0
  171. package/3.api/5.kit/10.runtime-config.md +27 -0
  172. package/3.api/5.kit/10.templates.md +283 -0
  173. package/3.api/5.kit/11.nitro.md +409 -0
  174. package/3.api/5.kit/12.resolving.md +268 -0
  175. package/3.api/5.kit/13.logging.md +65 -0
  176. package/3.api/5.kit/14.builder.md +491 -0
  177. package/3.api/5.kit/15.examples.md +41 -0
  178. package/3.api/5.kit/2.programmatic.md +125 -0
  179. package/3.api/5.kit/3.compatibility.md +230 -0
  180. package/3.api/5.kit/4.autoimports.md +144 -0
  181. package/3.api/5.kit/5.components.md +127 -0
  182. package/3.api/5.kit/6.context.md +130 -0
  183. package/3.api/5.kit/7.pages.md +295 -0
  184. package/3.api/5.kit/8.layout.md +80 -0
  185. package/3.api/5.kit/9.plugins.md +263 -0
  186. package/3.api/6.advanced/.navigation.yml +1 -0
  187. package/3.api/6.advanced/1.hooks.md +105 -0
  188. package/3.api/6.advanced/2.import-meta.md +60 -0
  189. package/3.api/6.nuxt-config.md +12 -0
  190. package/3.api/index.md +31 -0
  191. package/5.community/.navigation.yml +3 -0
  192. package/5.community/2.getting-help.md +48 -0
  193. package/5.community/3.reporting-bugs.md +50 -0
  194. package/5.community/4.contribution.md +205 -0
  195. package/5.community/5.framework-contribution.md +142 -0
  196. package/5.community/6.roadmap.md +79 -0
  197. package/5.community/7.changelog.md +92 -0
  198. package/6.bridge/.navigation.yml +3 -0
  199. package/6.bridge/1.overview.md +137 -0
  200. package/6.bridge/10.configuration.md +96 -0
  201. package/6.bridge/2.typescript.md +46 -0
  202. package/6.bridge/3.bridge-composition-api.md +132 -0
  203. package/6.bridge/4.plugins-and-middleware.md +65 -0
  204. package/6.bridge/5.nuxt3-compatible-api.md +204 -0
  205. package/6.bridge/6.meta.md +117 -0
  206. package/6.bridge/7.runtime-config.md +38 -0
  207. package/6.bridge/8.nitro.md +102 -0
  208. package/6.bridge/9.vite.md +37 -0
  209. package/7.migration/.navigation.yml +3 -0
  210. package/7.migration/1.overview.md +24 -0
  211. package/7.migration/10.bundling.md +28 -0
  212. package/7.migration/11.server.md +17 -0
  213. package/7.migration/2.configuration.md +240 -0
  214. package/7.migration/20.module-authors.md +94 -0
  215. package/7.migration/3.auto-imports.md +18 -0
  216. package/7.migration/4.meta.md +127 -0
  217. package/7.migration/5.plugins-and-middleware.md +80 -0
  218. package/7.migration/6.pages-and-layouts.md +233 -0
  219. package/7.migration/7.component-options.md +156 -0
  220. package/7.migration/8.runtime-config.md +58 -0
  221. package/LICENSE +21 -0
  222. package/README.md +11 -0
  223. package/package.json +16 -4
  224. package/dist/.gitkeep +0 -0
@@ -0,0 +1,294 @@
1
+ ---
2
+ title: 'useNuxtApp'
3
+ description: 'Access the shared runtime context of the Nuxt Application.'
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
+ `useNuxtApp` is a built-in composable that provides a way to access shared runtime context of Nuxt, also known as the [Nuxt context](/docs/guide/going-further/nuxt-app#the-nuxt-context), which is available on both client and server side (but not within Nitro routes). It helps you access the Vue app instance, runtime hooks, runtime config variables and internal states, such as `ssrContext` and `payload`.
12
+
13
+ ```vue [app.vue]
14
+ <script setup lang="ts">
15
+ const nuxtApp = useNuxtApp()
16
+ </script>
17
+ ```
18
+
19
+ If runtime context is unavailable in your scope, `useNuxtApp` will throw an exception when called. You can use [`tryUseNuxtApp`](#tryusenuxtapp) instead for composables that do not require `nuxtApp`, or to simply check if context is available or not without an exception.
20
+
21
+ <!--
22
+ note
23
+ By default, the shared runtime context of Nuxt is namespaced under the [`buildId`](/docs/api/nuxt-config#buildid) option. It allows the support of multiple runtime contexts.
24
+
25
+ ## Params
26
+
27
+ - `appName`: an optional application name. If you do not provide it, the Nuxt `buildId` option is used. Otherwise, it must match with an existing `buildId`. -->
28
+
29
+ ## Methods
30
+
31
+ ### `provide (name, value)`
32
+
33
+ `nuxtApp` is a runtime context that you can extend using [Nuxt plugins](/docs/guide/directory-structure/plugins). Use the `provide` function to create Nuxt plugins to make values and helper methods available in your Nuxt application across all composables and components.
34
+
35
+ `provide` function accepts `name` and `value` parameters.
36
+
37
+ ```js
38
+ const nuxtApp = useNuxtApp()
39
+ nuxtApp.provide('hello', (name) => `Hello ${name}!`)
40
+
41
+ // Prints "Hello name!"
42
+ console.log(nuxtApp.$hello('name'))
43
+ ```
44
+
45
+ As you can see in the example above, `$hello` has become the new and custom part of `nuxtApp` context and it is available in all places where `nuxtApp` is accessible.
46
+
47
+ ### `hook(name, cb)`
48
+
49
+ Hooks available in `nuxtApp` allows you to customize the runtime aspects of your Nuxt application. You can use runtime hooks in Vue.js composables and [Nuxt plugins](/docs/guide/directory-structure/plugins) to hook into the rendering lifecycle.
50
+
51
+ `hook` function is useful for adding custom logic by hooking into the rendering lifecycle at a specific point. `hook` function is mostly used when creating Nuxt plugins.
52
+
53
+ See [Runtime Hooks](/docs/api/advanced/hooks#app-hooks-runtime) for available runtime hooks called by Nuxt.
54
+
55
+ ```ts [plugins/test.ts]
56
+ export default defineNuxtPlugin((nuxtApp) => {
57
+ nuxtApp.hook('page:start', () => {
58
+ /* your code goes here */
59
+ })
60
+ nuxtApp.hook('vue:error', (..._args) => {
61
+ console.log('vue:error')
62
+ // if (import.meta.client) {
63
+ // console.log(..._args)
64
+ // }
65
+ })
66
+ })
67
+ ```
68
+
69
+ ### `callHook(name, ...args)`
70
+
71
+ `callHook` returns a promise when called with any of the existing hooks.
72
+
73
+ ```ts
74
+ await nuxtApp.callHook('my-plugin:init')
75
+ ```
76
+
77
+ ## Properties
78
+
79
+ `useNuxtApp()` exposes the following properties that you can use to extend and customize your app and share state, data and variables.
80
+
81
+ ### `vueApp`
82
+
83
+ `vueApp` is the global Vue.js [application instance](https://vuejs.org/api/application.html#application-api) that you can access through `nuxtApp`.
84
+
85
+ Some useful methods:
86
+ - [`component()`](https://vuejs.org/api/application.html#app-component) - Registers a global component if passing both a name string and a component definition, or retrieves an already registered one if only the name is passed.
87
+ - [`directive()`](https://vuejs.org/api/application.html#app-directive) - Registers a global custom directive if passing both a name string and a directive definition, or retrieves an already registered one if only the name is passed[(example)](/docs/guide/directory-structure/plugins#vue-directives).
88
+ - [`use()`](https://vuejs.org/api/application.html#app-use) - Installs a **[Vue.js Plugin](https://vuejs.org/guide/reusability/plugins.html)** [(example)](/docs/guide/directory-structure/plugins#vue-plugins).
89
+
90
+ :read-more{icon="i-simple-icons-vuedotjs" to="https://vuejs.org/api/application.html#application-api"}
91
+
92
+ ### `ssrContext`
93
+
94
+ `ssrContext` is generated during server-side rendering and it is only available on the server side.
95
+
96
+ Nuxt exposes the following properties through `ssrContext`:
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.
99
+ - `payload` (object) - NuxtApp payload object.
100
+
101
+ ### `payload`
102
+
103
+ `payload` exposes data and state variables from server side to client side. The following keys will be available on the client after they have been passed from the server side:
104
+
105
+ - `serverRendered` (boolean) - Indicates if response is server-side-rendered.
106
+ - `data` (object) - When you fetch the data from an API endpoint using either [`useFetch`](/docs/api/composables/use-fetch) or [`useAsyncData`](/docs/api/composables/use-async-data) , resulting payload can be accessed from the `payload.data`. This data is cached and helps you prevent fetching the same data in case an identical request is made more than once.
107
+
108
+ ::code-group
109
+ ```vue [app.vue]
110
+ <script setup lang="ts">
111
+ const { data } = await useAsyncData('count', () => $fetch('/api/count'))
112
+ </script>
113
+ ```
114
+ ```ts [server/api/count.ts]
115
+ export default defineEventHandler(event => {
116
+ return { count: 1 }
117
+ })
118
+ ```
119
+ ::
120
+
121
+ After fetching the value of `count` using [`useAsyncData`](/docs/api/composables/use-async-data) in the example above, if you access `payload.data`, you will see `{ count: 1 }` recorded there.
122
+
123
+ When accessing the same `payload.data` from [`ssrcontext`](#ssrcontext), you can access the same value on the server side as well.
124
+
125
+ - `state` (object) - When you use [`useState`](/docs/api/composables/use-state) composable in Nuxt to set shared state, this state data is accessed through `payload.state.[name-of-your-state]`.
126
+
127
+ ```ts [plugins/my-plugin.ts]
128
+ export const useColor = () => useState<string>('color', () => 'pink')
129
+
130
+ export default defineNuxtPlugin((nuxtApp) => {
131
+ if (import.meta.server) {
132
+ const color = useColor()
133
+ }
134
+ })
135
+ ```
136
+
137
+ It is also possible to use more advanced types, such as `ref`, `reactive`, `shallowRef`, `shallowReactive` and `NuxtError`.
138
+
139
+ Since [Nuxt v3.4](https://nuxt.com/blog/v3-4#payload-enhancements), it is possible to define your own reducer/reviver for types that are not supported by Nuxt.
140
+
141
+ :video-accordion{title="Watch a video from Alexander Lichter about serializing payloads, especially with regards to classes" videoId="8w6ffRBs8a4"}
142
+
143
+ In the example below, we define a reducer (or a serializer) and a reviver (or deserializer) for the [Luxon](https://moment.github.io/luxon/#/) DateTime class, using a payload plugin.
144
+
145
+ ```ts [plugins/date-time-payload.ts]
146
+ /**
147
+ * This kind of plugin runs very early in the Nuxt lifecycle, before we revive the payload.
148
+ * You will not have access to the router or other Nuxt-injected properties.
149
+ *
150
+ * Note that the "DateTime" string is the type identifier and must
151
+ * be the same on both the reducer and the reviver.
152
+ */
153
+ export default definePayloadPlugin((nuxtApp) => {
154
+ definePayloadReducer('DateTime', (value) => {
155
+ return value instanceof DateTime && value.toJSON()
156
+ })
157
+ definePayloadReviver('DateTime', (value) => {
158
+ return DateTime.fromISO(value)
159
+ })
160
+ })
161
+ ```
162
+
163
+ ### `isHydrating`
164
+
165
+ Use `nuxtApp.isHydrating` (boolean) to check if the Nuxt app is hydrating on the client side.
166
+
167
+ ```ts [components/nuxt-error-boundary.ts]
168
+ export default defineComponent({
169
+ setup (_props, { slots, emit }) {
170
+ const nuxtApp = useNuxtApp()
171
+ onErrorCaptured((err) => {
172
+ if (import.meta.client && !nuxtApp.isHydrating) {
173
+ // ...
174
+ }
175
+ })
176
+ }
177
+ })
178
+ ```
179
+
180
+ ### `runWithContext`
181
+
182
+ ::note
183
+ You are likely here because you got a "Nuxt instance unavailable" message. Please use this method sparingly, and report examples that are causing issues, so that it can ultimately be solved at the framework level.
184
+ ::
185
+
186
+ The `runWithContext` method is meant to be used to call a function and give it an explicit Nuxt context. Typically, the Nuxt context is passed around implicitly and you do not need to worry about this. However, when working with complex `async`/`await` scenarios in middleware/plugins, you can run into instances where the current instance has been unset after an async call.
187
+
188
+ ```ts [middleware/auth.ts]
189
+ export default defineNuxtRouteMiddleware(async (to, from) => {
190
+ const nuxtApp = useNuxtApp()
191
+ let user
192
+ try {
193
+ user = await fetchUser()
194
+ // the Vue/Nuxt compiler loses context here because of the try/catch block.
195
+ } catch (e) {
196
+ user = null
197
+ }
198
+ if (!user) {
199
+ // apply the correct Nuxt context to our `navigateTo` call.
200
+ return nuxtApp.runWithContext(() => navigateTo('/auth'))
201
+ }
202
+ })
203
+ ```
204
+
205
+ #### Usage
206
+
207
+ ```js
208
+ const result = nuxtApp.runWithContext(() => functionWithContext())
209
+ ```
210
+
211
+ - `functionWithContext`: Any function that requires the context of the current Nuxt application. This context will be correctly applied automatically.
212
+
213
+ `runWithContext` will return whatever is returned by `functionWithContext`.
214
+
215
+ #### A Deeper Explanation of Context
216
+
217
+ Vue.js Composition API (and Nuxt composables similarly) work by depending on an implicit context. During the lifecycle, Vue sets the temporary instance of the current component (and Nuxt temporary instance of nuxtApp) to a global variable and unsets it in same tick. When rendering on the server side, there are multiple requests from different users and nuxtApp running in a same global context. Because of this, Nuxt and Vue immediately unset this global instance to avoid leaking a shared reference between two users or components.
218
+
219
+ What it does mean? The Composition API and Nuxt Composables are only available during lifecycle and in same tick before any async operation:
220
+
221
+ ```js
222
+ // --- Vue internal ---
223
+ const _vueInstance = null
224
+ const getCurrentInstance = () => _vueInstance
225
+ // ---
226
+
227
+ // Vue / Nuxt sets a global variable referencing to current component in _vueInstance when calling setup()
228
+ async function setup() {
229
+ getCurrentInstance() // Works
230
+ await someAsyncOperation() // Vue unsets the context in same tick before async operation!
231
+ getCurrentInstance() // null
232
+ }
233
+ ```
234
+
235
+ The classic solution to this, is caching the current instance on first call to a local variable like `const instance = getCurrentInstance()` and use it in the next composable call but the issue is that any nested composable calls now needs to explicitly accept the instance as an argument and not depend on the implicit context of composition-api. This is design limitation with composables and not an issue per-se.
236
+
237
+ To overcome this limitation, Vue does some behind the scenes work when compiling our application code and restores context after each call for `<script setup>`:
238
+
239
+ ```js
240
+ const __instance = getCurrentInstance() // Generated by Vue compiler
241
+ getCurrentInstance() // Works!
242
+ await someAsyncOperation() // Vue unsets the context
243
+ __restoreInstance(__instance) // Generated by Vue compiler
244
+ getCurrentInstance() // Still works!
245
+ ```
246
+
247
+ For a better description of what Vue actually does, see [unjs/unctx#2 (comment)](https://github.com/unjs/unctx/issues/2#issuecomment-942193723).
248
+
249
+ #### Solution
250
+
251
+ This is where `runWithContext` can be used to restore context, similarly to how `<script setup>` works.
252
+
253
+ Nuxt internally uses [unjs/unctx](https://github.com/unjs/unctx) to support composables similar to Vue for plugins and middleware. This enables composables like `navigateTo()` to work without directly passing `nuxtApp` to them - bringing the DX and performance benefits of Composition API to the whole Nuxt framework.
254
+
255
+ Nuxt composables have the same design as the Vue Composition API and therefore need a similar solution to magically do this transform. Check out [unjs/unctx#2](https://github.com/unjs/unctx/issues/2) (proposal), [unjs/unctx#4](https://github.com/unjs/unctx/pull/4) (transform implementation), and [nuxt/framework#3884](https://github.com/nuxt/framework/pull/3884) (Integration to Nuxt).
256
+
257
+ Vue currently only supports async context restoration for `<script setup>` for async/await usage. In Nuxt, the transform support for `defineNuxtPlugin()` and `defineNuxtRouteMiddleware()` was added, which means when you use them Nuxt automatically transforms them with context restoration.
258
+
259
+ #### Remaining Issues
260
+
261
+ The `unjs/unctx` transformation to automatically restore context seems buggy with `try/catch` statements containing `await` which ultimately needs to be solved in order to remove the requirement of the workaround suggested above.
262
+
263
+ #### Native Async Context
264
+
265
+ Using a new experimental feature, it is possible to enable native async context support using [Node.js `AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and new unctx support to make async context available **natively** to **any nested async composable** without needing a transform or manual passing/calling with context.
266
+
267
+ ::tip
268
+ Native async context support works currently in Bun and Node.
269
+ ::
270
+
271
+ :read-more{to="/docs/guide/going-further/experimental-features#asynccontext"}
272
+
273
+ ## tryUseNuxtApp
274
+
275
+ This function works exactly the same as `useNuxtApp`, but returns `null` if context is unavailable instead of throwing an exception.
276
+
277
+ You can use it for composables that do not require `nuxtApp`, or to simply check if context is available or not without an exception.
278
+
279
+ Example usage:
280
+
281
+ ```ts [composable.ts]
282
+ export function useStandType() {
283
+ // Always works on the client
284
+ if (tryUseNuxtApp()) {
285
+ return useRuntimeConfig().public.STAND_TYPE
286
+ } else {
287
+ return process.env.STAND_TYPE
288
+ }
289
+ }
290
+ ```
291
+
292
+ <!-- ### Params
293
+
294
+ - `appName`: an optional application name. If you do not provide it, the Nuxt `buildId` option is used. Otherwise, it must match with an existing `buildId`. -->
@@ -0,0 +1,112 @@
1
+ ---
2
+ title: 'useNuxtData'
3
+ description: 'Access the current cached value of data fetching composables.'
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/asyncData.ts
8
+ size: xs
9
+ ---
10
+
11
+ ::note
12
+ `useNuxtData` gives you access to the current cached value of [`useAsyncData`](/docs/api/composables/use-async-data) , [`useLazyAsyncData`](/docs/api/composables/use-lazy-async-data), [`useFetch`](/docs/api/composables/use-fetch) and [`useLazyFetch`](/docs/api/composables/use-lazy-fetch) with explicitly provided key.
13
+ ::
14
+
15
+ ## Usage
16
+
17
+ The `useNuxtData` composable is used to access the current cached value of data-fetching composables such as `useAsyncData`, `useLazyAsyncData`, `useFetch`, and `useLazyFetch`. By providing the key used during the data fetch, you can retrieve the cached data and use it as needed.
18
+
19
+ This is particularly useful for optimizing performance by reusing already-fetched data or implementing features like Optimistic Updates or cascading data updates.
20
+
21
+ To use `useNuxtData`, ensure that the data-fetching composable (`useFetch`, `useAsyncData`, etc.) has been called with an explicitly provided key.
22
+
23
+ :video-accordion{title="Watch a video from LearnVue about useNuxtData" videoId="e-_u6swXRWk"}
24
+
25
+ ## Params
26
+
27
+ - `key`: The unique key that identifies the cached data. This key should match the one used during the original data fetch.
28
+
29
+ ## Return Values
30
+
31
+ - `data`: A reactive reference to the cached data associated with the provided key. If no cached data exists, the value will be `null`. This `Ref` automatically updates if the cached data changes, allowing seamless reactivity in your components.
32
+
33
+ ## Example
34
+
35
+ The example below shows how you can use cached data as a placeholder while the most recent data is being fetched from the server.
36
+
37
+ ```vue [pages/posts.vue]
38
+ <script setup lang="ts">
39
+ // We can access same data later using 'posts' key
40
+ const { data } = await useFetch('/api/posts', { key: 'posts' })
41
+ </script>
42
+ ```
43
+
44
+ ```vue [pages/posts/[id\\].vue]
45
+ <script setup lang="ts">
46
+ // Access to the cached value of useFetch in posts.vue (parent route)
47
+ const { data: posts } = useNuxtData('posts')
48
+
49
+ const route = useRoute()
50
+
51
+ const { data } = useLazyFetch(`/api/posts/${route.params.id}`, {
52
+ key: `post-${route.params.id}`,
53
+ default() {
54
+ // Find the individual post from the cache and set it as the default value.
55
+ return posts.value.find(post => post.id === route.params.id)
56
+ }
57
+ })
58
+ </script>
59
+ ```
60
+
61
+ ## Optimistic Updates
62
+
63
+ The example below shows how implementing Optimistic Updates can be achieved using useNuxtData.
64
+
65
+ Optimistic Updates is a technique where the user interface is updated immediately, assuming a server operation will succeed. If the operation eventually fails, the UI is rolled back to its previous state.
66
+
67
+ ```vue [pages/todos.vue]
68
+ <script setup lang="ts">
69
+ // We can access same data later using 'todos' key
70
+ const { data } = await useAsyncData('todos', () => $fetch('/api/todos'))
71
+ </script>
72
+ ```
73
+
74
+ ```vue [components/NewTodo.vue]
75
+ <script setup lang="ts">
76
+ const newTodo = ref('')
77
+ let previousTodos = []
78
+
79
+ // Access to the cached value of useAsyncData in todos.vue
80
+ const { data: todos } = useNuxtData('todos')
81
+
82
+ async function addTodo () {
83
+ return $fetch('/api/addTodo', {
84
+ method: 'post',
85
+ body: {
86
+ todo: newTodo.value
87
+ },
88
+ onRequest () {
89
+ // Store the previously cached value to restore if fetch fails.
90
+ previousTodos = todos.value
91
+
92
+ // Optimistically update the todos.
93
+ todos.value = [...todos.value, newTodo.value]
94
+ },
95
+ onResponseError () {
96
+ // Rollback the data if the request failed.
97
+ todos.value = previousTodos
98
+ },
99
+ async onResponse () {
100
+ // Invalidate todos in the background if the request succeeded.
101
+ await refreshNuxtData('todos')
102
+ }
103
+ })
104
+ }
105
+ </script>
106
+ ```
107
+
108
+ ## Type
109
+
110
+ ```ts
111
+ useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null> }
112
+ ```
@@ -0,0 +1,118 @@
1
+ ---
2
+ title: "usePreviewMode"
3
+ description: "Use usePreviewMode to check and control preview mode in Nuxt"
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/preview.ts
8
+ size: xs
9
+ ---
10
+
11
+ # `usePreviewMode`
12
+
13
+ Preview mode allows you to see how your changes would be displayed on a live site without revealing them to users.
14
+
15
+ You can use the built-in `usePreviewMode` composable to access and control preview state in Nuxt. If the composable detects preview mode it will automatically force any updates necessary for [`useAsyncData`](/docs/api/composables/use-async-data) and [`useFetch`](/docs/api/composables/use-fetch) to rerender preview content.
16
+
17
+ ```js
18
+ const { enabled, state } = usePreviewMode()
19
+ ```
20
+
21
+ ## Options
22
+
23
+ ### Custom `enable` check
24
+
25
+ You can specify a custom way to enable preview mode. By default the `usePreviewMode` composable will enable preview mode if there is a `preview` param in url that is equal to `true` (for example, `http://localhost:3000?preview=true`). You can wrap the `usePreviewMode` into custom composable, to keep options consistent across usages and prevent any errors.
26
+
27
+ ```js
28
+ export function useMyPreviewMode () {
29
+ return usePreviewMode({
30
+ shouldEnable: () => {
31
+ return !!route.query.customPreview
32
+ }
33
+ });
34
+ }
35
+ ```
36
+
37
+ ### Modify default state
38
+
39
+ `usePreviewMode` will try to store the value of a `token` param from url in state. You can modify this state and it will be available for all [`usePreviewMode`](/docs/api/composables/use-preview-mode) calls.
40
+
41
+ ```js
42
+ const data1 = ref('data1')
43
+
44
+ const { enabled, state } = usePreviewMode({
45
+ getState: (currentState) => {
46
+ return { data1, data2: 'data2' }
47
+ }
48
+ })
49
+ ```
50
+
51
+ ::note
52
+ The `getState` function will append returned values to current state, so be careful not to accidentally overwrite important state.
53
+ ::
54
+
55
+ ### Customize the `onEnable` and `onDisable` callbacks
56
+
57
+ By default, when `usePreviewMode` is enabled, it will call `refreshNuxtData()` to re-fetch all data from the server.
58
+
59
+ When preview mode is disabled, the composable will attach a callback to call `refreshNuxtData()` to run after a subsequent router navigation.
60
+
61
+ You can specify custom callbacks to be triggered by providing your own functions for the `onEnable` and `onDisable` options.
62
+
63
+ ```js
64
+ const { enabled, state } = usePreviewMode({
65
+ onEnable: () => {
66
+ console.log('preview mode has been enabled')
67
+ },
68
+ onDisable: () => {
69
+ console.log('preview mode has been disabled')
70
+ }
71
+ })
72
+ ```
73
+
74
+ ## Example
75
+
76
+ The example below creates a page where part of a content is rendered only in preview mode.
77
+
78
+ ```vue [pages/some-page.vue]
79
+ <script setup>
80
+ const { enabled, state } = usePreviewMode()
81
+
82
+ const { data } = await useFetch('/api/preview', {
83
+ query: {
84
+ apiKey: state.token
85
+ }
86
+ })
87
+ </script>
88
+
89
+ <template>
90
+ <div>
91
+ Some base content
92
+ <p v-if="enabled">
93
+ Only preview content: {{ state.token }}
94
+ <br>
95
+ <button @click="enabled = false">
96
+ disable preview mode
97
+ </button>
98
+ </p>
99
+ </div>
100
+ </template>
101
+ ```
102
+
103
+ Now you can generate your site and serve it:
104
+
105
+ ```bash [Terminal]
106
+ npx nuxi generate
107
+ npx nuxi preview
108
+ ```
109
+
110
+ Then you can see your preview page by adding the query param `preview` to the end of the page you want to see once:
111
+
112
+ ```js
113
+ ?preview=true
114
+ ```
115
+
116
+ ::note
117
+ `usePreviewMode` should be tested locally with `nuxi generate` and then `nuxi preview` rather than `nuxi dev`. (The [preview command](/docs/api/commands/preview) is not related to preview mode.)
118
+ ::
@@ -0,0 +1,23 @@
1
+ ---
2
+ title: 'useRequestEvent'
3
+ description: 'Access the incoming request event with the useRequestEvent composable.'
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/ssr.ts
8
+ size: xs
9
+ ---
10
+
11
+ Within the [Nuxt context](/docs/guide/going-further/nuxt-app#the-nuxt-context) you can use `useRequestEvent` to access the incoming request.
12
+
13
+ ```ts
14
+ // Get underlying request event
15
+ const event = useRequestEvent()
16
+
17
+ // Get the URL
18
+ const url = event?.path
19
+ ```
20
+
21
+ ::tip
22
+ In the browser, `useRequestEvent` will return `undefined`.
23
+ ::
@@ -0,0 +1,52 @@
1
+ ---
2
+ title: 'useRequestFetch'
3
+ description: 'Forward the request context and headers for server-side fetch requests with the useRequestFetch composable.'
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/ssr.ts
8
+ size: xs
9
+ ---
10
+
11
+ You can use `useRequestFetch` to forward the request context and headers when making server-side fetch requests.
12
+
13
+ When making a client-side fetch request, the browser automatically sends the necessary headers.
14
+ However, when making a request during server-side rendering, due to security considerations, we need to forward the headers manually.
15
+
16
+ ::note
17
+ Headers that are **not meant to be forwarded** will **not be included** in the request. These headers include, for example:
18
+ `transfer-encoding`, `connection`, `keep-alive`, `upgrade`, `expect`, `host`, `accept`
19
+ ::
20
+
21
+ ::tip
22
+ The [`useFetch`](/docs/api/composables/use-fetch) composable uses `useRequestFetch` under the hood to automatically forward the request context and headers.
23
+ ::
24
+
25
+ ::code-group
26
+
27
+ ```vue [pages/index.vue]
28
+ <script setup lang="ts">
29
+ // This will forward the user's headers to the `/api/cookies` event handler
30
+ // Result: { cookies: { foo: 'bar' } }
31
+ const requestFetch = useRequestFetch()
32
+ const { data: forwarded } = await useAsyncData(() => requestFetch('/api/cookies'))
33
+
34
+ // This will NOT forward anything
35
+ // Result: { cookies: {} }
36
+ const { data: notForwarded } = await useAsyncData(() => $fetch('/api/cookies'))
37
+ </script>
38
+ ```
39
+
40
+ ```ts [server/api/cookies.ts]
41
+ export default defineEventHandler((event) => {
42
+ const cookies = parseCookies(event)
43
+
44
+ return { cookies }
45
+ })
46
+ ```
47
+
48
+ ::
49
+
50
+ ::tip
51
+ In the browser during client-side navigation, `useRequestFetch` will behave just like regular [`$fetch`](/docs/api/utils/dollarfetch).
52
+ ::
@@ -0,0 +1,34 @@
1
+ ---
2
+ title: "useRequestHeader"
3
+ description: "Use useRequestHeader to access a certain incoming request header."
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/ssr.ts
8
+ size: xs
9
+ ---
10
+
11
+ You can use the built-in [`useRequestHeader`](/docs/api/composables/use-request-header) composable to access any incoming request header within your pages, components, and plugins.
12
+
13
+ ```ts
14
+ // Get the authorization request header
15
+ const authorization = useRequestHeader('authorization')
16
+ ```
17
+
18
+ ::tip
19
+ In the browser, `useRequestHeader` will return `undefined`.
20
+ ::
21
+
22
+ ## Example
23
+
24
+ We can use `useRequestHeader` to easily figure out if a user is authorized or not.
25
+
26
+ The example below reads the `authorization` request header to find out if a person can access a restricted resource.
27
+
28
+ ```ts [middleware/authorized-only.ts]
29
+ export default defineNuxtRouteMiddleware((to, from) => {
30
+ if (!useRequestHeader('authorization')) {
31
+ return navigateTo('/not-authorized')
32
+ }
33
+ })
34
+ ```
@@ -0,0 +1,37 @@
1
+ ---
2
+ title: "useRequestHeaders"
3
+ description: "Use useRequestHeaders to access the incoming request headers."
4
+ links:
5
+ - label: Source
6
+ icon: i-simple-icons-github
7
+ to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/ssr.ts
8
+ size: xs
9
+ ---
10
+
11
+ You can use built-in [`useRequestHeaders`](/docs/api/composables/use-request-headers) composable to access the incoming request headers within your pages, components, and plugins.
12
+
13
+ ```js
14
+ // Get all request headers
15
+ const headers = useRequestHeaders()
16
+
17
+ // Get only cookie request header
18
+ const headers = useRequestHeaders(['cookie'])
19
+ ```
20
+
21
+ ::tip
22
+ In the browser, `useRequestHeaders` will return an empty object.
23
+ ::
24
+
25
+ ## Example
26
+
27
+ We can use `useRequestHeaders` to access and proxy the initial request's `authorization` header to any future internal requests during SSR.
28
+
29
+ The example below adds the `authorization` request header to an isomorphic `$fetch` call.
30
+
31
+ ```vue [pages/some-page.vue]
32
+ <script setup lang="ts">
33
+ const { data } = await useFetch('/api/confidential', {
34
+ headers: useRequestHeaders(['authorization'])
35
+ })
36
+ </script>
37
+ ```