diff --git a/packages/nuxt/global.d.ts b/packages/nuxt/global.d.ts new file mode 100644 index 0000000000..cc0c1cb92a --- /dev/null +++ b/packages/nuxt/global.d.ts @@ -0,0 +1,2 @@ +// Global compile-time constants +declare var __TEST__: boolean diff --git a/packages/nuxt/playground/pages/usage-after-await.vue b/packages/nuxt/playground/pages/usage-after-await.vue new file mode 100644 index 0000000000..d54661dbcb --- /dev/null +++ b/packages/nuxt/playground/pages/usage-after-await.vue @@ -0,0 +1,24 @@ + + + diff --git a/packages/nuxt/src/runtime/composables.ts b/packages/nuxt/src/runtime/composables.ts index e0f027c2d4..9b2e312406 100644 --- a/packages/nuxt/src/runtime/composables.ts +++ b/packages/nuxt/src/runtime/composables.ts @@ -1,5 +1,33 @@ import { useNuxtApp } from '#app' -import type { Pinia } from 'pinia' +import { + defineStore as _defineStore, + type Pinia, + type StoreGeneric, +} from 'pinia' export * from 'pinia' -export const usePinia = () => useNuxtApp().$pinia as Pinia +export const usePinia = () => useNuxtApp().$pinia as Pinia | undefined + +export const defineStore: typeof _defineStore = + process.env.NODE_ENV === 'production' && !__TEST__ + ? _defineStore + : ((( + ...args: Parameters + ): ReturnType => { + if (!import.meta.server) { + return _defineStore(...args) + } + + const originalUseStore = _defineStore(...args) + function useStore( + pinia?: Pinia | null, + hot?: StoreGeneric + ): StoreGeneric { + return originalUseStore(pinia || usePinia(), hot) + } + + useStore.$id = originalUseStore.$id + useStore._pinia = originalUseStore._pinia + + return useStore + }) as typeof _defineStore) diff --git a/packages/nuxt/test/nuxt.spec.ts b/packages/nuxt/test/nuxt.spec.ts index ac5e0b4da1..6978977cd2 100644 --- a/packages/nuxt/test/nuxt.spec.ts +++ b/packages/nuxt/test/nuxt.spec.ts @@ -37,4 +37,10 @@ describe('Nuxt', async () => { it('can auto import from layers', async () => { expect(await $fetch('/')).toContain('Layer store: 0') }) + + it('throws an error server-side when the nuxt context is not available', async () => { + await expect($fetch('/usage-after-await')).rejects.toThrowError( + '[nuxt] instance unavailable' + ) + }) }) diff --git a/packages/nuxt/tsconfig.json b/packages/nuxt/tsconfig.json index 3666c452fc..9fc3ea221f 100644 --- a/packages/nuxt/tsconfig.json +++ b/packages/nuxt/tsconfig.json @@ -2,6 +2,7 @@ "extends": "./playground/.nuxt/tsconfig.json", "include": [ "./shims.d.ts", + "./global.d.ts", // missing in the playground "./src" ]