diff --git a/docs/2.guide/3.going-further/1.experimental-features.md b/docs/2.guide/3.going-further/1.experimental-features.md index 8a24b16db4..6f18fada86 100644 --- a/docs/2.guide/3.going-further/1.experimental-features.md +++ b/docs/2.guide/3.going-further/1.experimental-features.md @@ -12,6 +12,14 @@ Internally, Nuxt uses `@nuxt/schema` to define these experimental features. You Note that these features are experimental and could be removed or modified in the future. :: +## asyncContext + +Enable native async context to be accessable for nested composables in Nuxt and in Nitro. See [full explanation in #20918](https://github.com/nuxt/nuxt/pull/20918). + +```ts [nuxt.config.ts] +export defineNuxtConfig({ experimental: { asyncContext: true } }) +``` + ## asyncEntry Enables generation of an async entry point for the Vue bundle, aiding module federation support. diff --git a/docs/3.api/1.composables/use-nuxt-app.md b/docs/3.api/1.composables/use-nuxt-app.md index f8ddf42b73..da1501abdf 100644 --- a/docs/3.api/1.composables/use-nuxt-app.md +++ b/docs/3.api/1.composables/use-nuxt-app.md @@ -144,3 +144,112 @@ export default defineComponent({ } }) ``` + +### `runWithContext` + +::alert + +

+ +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. + +

+ +:: + +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. + +```js +export default defineNuxtRouteMiddleware(async (to, from) => { + const nuxtApp = useNuxtApp() + let user + try { + user = await fetchUser() + // the Vue/Nuxt compiler loses context here because of the try/catch block. + } catch (e) { + user = null + } + if (!user) { + // apply the correct Nuxt context to our `navigateTo` call. + return nuxtApp.runWithContext(() => navigateTo('/auth')) + } +}) +``` + +#### Usage + +```js +const result = nuxtApp.runWithContext(() => functionWithContext()) +``` + +##### `functionWithContext` + +Any function that requires the context of the current Nuxt application. This context will be correctly applied automatically. + +##### Return value + +`runWithContext` will return whatever is returned by `functionWithContext`. + +#### A Deeper Explanation of Context + +##### Background + +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. + +What it does mean? The Composition API and Nuxt Composables are only available during lifecycle and in same tick before any async operation: + +```js +// --- Vue internal --- +const _vueInstance = null +const getCurrentInstance = () => _vueInstance +// --- + +// Vue / Nuxt sets a global variable referencing to current component in _vueInstance when calling setup() +async function setup() { + getCurrentInstance() // Works + await someAsyncOperation() // Vue unsets the context in same tick before async operation! + getCurrentInstance() // null +} +``` + +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. + +To overcome this limitation, Vue does some behind the scenes work when compiling our application code and restores context after each call for `