I’m trying to share a Pinia store between two Vue applications by putting it in a common NPM package. Both apps need to use the same store logic, so I thought it would be great to extract it into a shared utility package.
Here’s how I set up the store:
export const useSharedStore = defineStore('shared', () => {
// store logic here
})
In my package index file, I export it like this:
import { useSharedStore } from './stores/SharedStore'
export {
useSharedStore
}
When I try to use this store in a Vue component after importing it from the NPM package, I get this error:
getActivePinia() was called but there was no active Pinia. Are you trying to use a store before calling app.use(pinia)?
This is confusing because I have properly set up Pinia in my main.ts file with createPinia() and app.use(pinia). All my local stores work perfectly fine.
Is it possible to share Pinia stores through external packages? What could I be doing wrong here?
This happens because your NPM module bundles its own copy of Pinia dependencies. Your store tries to access a different Pinia instance than what’s configured in your main app. I hit this exact issue building a component library with shared state management. Fix it by making Pinia a peer dependency in your package.json instead of a regular dependency, and make sure your build process externalizes Pinia. Also check your bundler config isn’t creating separate instances. What worked for me was initializing the store lazily in the consuming app rather than at the package level - ensures it uses the right Pinia context.
yeah, this trips up a lot of ppl when sharing stores between apps. the timing’s off - your shared store initializes before the main app’s pinia instance is ready. wrap ur store usage in a composable that checks if pinia’s active first, or delay store creation until after app mounts. I just export the store definition without calling defineStore right away, then let each app create its own instance when it’s ready.
I encountered a similar problem while working with micro-frontends. The issue arises because your shared package initializes its own Pinia context, which conflicts with your main application’s context. You can resolve this by modifying your store to accept a Pinia instance as a parameter instead of relying on a global instance:
export const createSharedStore = (pinia) => {
return defineStore('shared', () => {
// store logic here
})(pinia);
}
This way, each application can provide its own Pinia instance while still utilizing the same store logic. Although you could handle errors with getActivePinia(), the parameter method has proven to be more dependable.