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..adc86268d0 --- /dev/null +++ b/packages/nuxt/playground/pages/usage-after-await.vue @@ -0,0 +1,17 @@ + + + + + Count: {{ counter.$state.count }} + + + + diff --git a/packages/nuxt/src/runtime/composables.ts b/packages/nuxt/src/runtime/composables.ts index 07fcf54767..098511a766 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 defineStore = (...args) => { + if (!import.meta.server) { + return _defineStore(...args) + } + + const store = _defineStore(...args) + + function useStore(pinia?: Pinia | null, hot?: StoreGeneric): StoreGeneric { + if (pinia) { + return store(pinia, hot) + } + + return store(usePinia(), hot) + } + + return useStore +} diff --git a/packages/nuxt/test/nuxt.spec.ts b/packages/nuxt/test/nuxt.spec.ts index 8bcbfccc05..a1bd848258 100644 --- a/packages/nuxt/test/nuxt.spec.ts +++ b/packages/nuxt/test/nuxt.spec.ts @@ -33,4 +33,8 @@ 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.toThrow() + }) })
Count: {{ counter.$state.count }}