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..64af35d2ed --- /dev/null +++ b/packages/nuxt/playground/pages/usage-after-await.vue @@ -0,0 +1,24 @@ + + + + + Count: {{ counter.$state.count }} + + + + diff --git a/packages/nuxt/src/runtime/composables.ts b/packages/nuxt/src/runtime/composables.ts index 07fcf54767..93fdc60a55 100644 --- a/packages/nuxt/src/runtime/composables.ts +++ b/packages/nuxt/src/runtime/composables.ts @@ -1,4 +1,27 @@ import { useNuxtApp } from '#app' +import { + defineStore as _defineStore, + type Pinia, + type StoreGeneric, +} from 'pinia' export * from 'pinia' -export const usePinia = () => useNuxtApp().$pinia +export const usePinia = () => useNuxtApp().$pinia as Pinia | undefined + +export const defineStore: typeof _defineStore = ( + ...args: [idOrOptions: any, setup?: any, setupOptions?: any] +) => { + 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 +} diff --git a/packages/nuxt/test/nuxt.spec.ts b/packages/nuxt/test/nuxt.spec.ts index 8bcbfccc05..1e082e4b8c 100644 --- a/packages/nuxt/test/nuxt.spec.ts +++ b/packages/nuxt/test/nuxt.spec.ts @@ -33,4 +33,10 @@ describe('works with nuxt', async () => { expect(html).not.toContain('I should not be serialized or hydrated') expect(html).toContain('skipHydrate-wrapped state is correct') }) + + 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' + ) + }) })
Count: {{ counter.$state.count }}