2021-11-21 16:14:46 +00:00
import { getContext } from 'unctx'
import type { Nuxt } from '@nuxt/schema'
2025-01-08 15:22:31 +00:00
import { asyncNameStorage } from './utils'
2025-01-09 14:04:13 +00:00
import { logger } from './logger'
2021-11-21 16:14:46 +00:00
2025-01-11 16:52:20 +00:00
/** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
export const getNuxtCtx = ( ) = > getContext < Nuxt > ( asyncNameStorage . getStore ( ) ! )
2025-01-11 20:36:15 +00:00
/** Global nuxt ctx - see https://github.com/unjs/unctx. */
export const nuxtCtx = getContext < Nuxt > ( 'nuxt-global' )
2021-11-21 16:14:46 +00:00
2022-04-04 09:41:48 +00:00
// TODO: Use use/tryUse from unctx. https://github.com/unjs/unctx/issues/6
2021-11-21 16:14:46 +00:00
/ * *
2022-04-04 09:41:48 +00:00
* Get access to Nuxt instance .
*
* Throws an error if Nuxt instance is unavailable .
2021-11-21 16:14:46 +00:00
* @example
* ` ` ` js
* const nuxt = useNuxt ( )
* ` ` `
* /
2022-04-04 09:41:48 +00:00
export function useNuxt ( ) : Nuxt {
2025-01-11 16:52:20 +00:00
const instance = getNuxtCtx ( ) . tryUse ( )
2022-04-04 09:41:48 +00:00
if ( ! instance ) {
2025-01-11 20:36:15 +00:00
const fallbackInstance = nuxtCtx . tryUse ( )
2025-01-09 14:04:13 +00:00
if ( fallbackInstance ) {
logger . warn ( 'Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.' )
2025-01-09 14:46:41 +00:00
return fallbackInstance
}
2022-04-04 09:41:48 +00:00
throw new Error ( 'Nuxt instance is unavailable!' )
}
return instance
}
/ * *
* Get access to Nuxt instance .
*
* Returns null if Nuxt instance is unavailable .
* @example
* ` ` ` js
* const nuxt = tryUseNuxt ( )
* if ( nuxt ) {
* // Do something
* }
* ` ` `
* /
export function tryUseNuxt ( ) : Nuxt | null {
2025-01-11 16:52:20 +00:00
const nuxt = getNuxtCtx ( ) . tryUse ( )
2025-01-09 14:46:41 +00:00
if ( ! nuxt ) {
2025-01-09 14:04:13 +00:00
logger . warn ( 'Using fallback global Nuxt instance. You may be using a @nuxt/kit composable outside of a Nuxt context, this behavior is deprecated and will be removed in v4.' )
2025-01-11 20:36:15 +00:00
return nuxtCtx . tryUse ( )
2025-01-09 14:04:13 +00:00
}
return nuxt
2022-04-04 09:41:48 +00:00
}