useNuxtApp is a built-in composable that provides a way to access shared runtime context of Nuxt, also known as 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.
Usage
[app/app.vue]
useNuxtApp will throw an exception when called. You can use tryUseNuxtApp instead for composables that do not require nuxtApp, or to simply check if context is available or not without an exception.
Methods
provide(name, value)
nuxtApp is a runtime context that you can extend using Nuxt 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.
The name of the value to provide. Will be accessible as
$name on the nuxtApp context.The value or helper function to make available.
hook(name, cb)
Hooks available innuxtApp allows you to customize the runtime aspects of your Nuxt application. You can use runtime hooks in Vue.js composables and Nuxt plugins to hook into the rendering lifecycle.
The name of the hook to listen to. See Runtime Hooks for available hooks.
The callback function to execute when the hook is triggered.
[app/plugins/test.ts]
callHook(name, …args)
callHook returns a promise when called with any of the existing hooks.
The name of the hook to call.
Arguments to pass to the hook handlers.
A promise that resolves when all hook handlers have completed.
Properties
vueApp
vueApp is the global Vue.js application instance that you can access through nuxtApp.
The Vue application instance with methods like
component(), directive(), and use().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.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.use()- Installs a Vue.js Plugin.
ssrContext
ssrContext is generated during server-side rendering and it is only available on the server side.
payload
payload exposes data and state variables from server side to client side.
isHydrating
UsenuxtApp.isHydrating to check if the Nuxt app is hydrating on the client side.
Whether the Nuxt app is currently hydrating on the client side.
[app/components/nuxt-error-boundary.ts]
runWithContext(fn)
TherunWithContext method is meant to be used to call a function and give it an explicit Nuxt context.
Any function that requires the context of the current Nuxt application.
Returns whatever is returned by the provided function.
[app/middleware/auth.ts]
tryUseNuxtApp
This function works exactly the same asuseNuxtApp, but returns null if context is unavailable instead of throwing an exception.
The NuxtApp instance if context is available, otherwise
null.[composable.ts]