MaxCodes
MaxCodes

Reputation: 94

Pinia: Cannot access store from Nuxt3 API

I have a Nuxt3 project with an Api in server/api/<api-endpoints>. Inside an endpoint, when I try to use a Pinia Store it says:

[nuxt] [request error] [🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?

or when I try to access a composable function from composables it cannot define any variable (says xxx is undefined even though it works in components so it just can't define anything in the function).

Pinia example inside server/api/token

import { useAuthStore } from "../stores/useAuthStore";
export default async (req: any, res: any) => {
    const authStore = useAuthStore()
    return authStore.access_token
};

Composable example inside server/api/user

import { useUserLogin } from "../../composables/useUserLogin";
export default async (req: any, res: any) => {
    const userLogin = useUserLogin()
    return twitchLogin.is_logged_in
};

Upvotes: 3

Views: 3432

Answers (2)

Mike
Mike

Reputation: 21

I ran into a similar issue trying to do something similar. When I ran nuxi dev const authStore = useAuthStore() will run. However when you nuxi build and run the output you will encounter the same error.

Since this is happening outside of setup I had to pass the $pinia context to the useStore. (Documented here https://pinia.vuejs.org/ssr/nuxt.html#using-the-store-outside-of-setup)

i.e.

import { useAuthStore } from "../stores/useAuthStore";
export default async (req: any, res: any) => {
    const { $pinia } = useNuxtApp()
    const authStore = useAuthStore($pinia)
    return authStore.access_token
};

Upvotes: 1

un1t
un1t

Reputation: 4449

I solved it by renaming buildModules to modules in nuxt.config.js

Nuxt modules are now build-time-only, and the buildModules property used in Nuxt 2 is deprecated in favor of modules.

// nuxt.config.js
export default defineNuxtConfig({
  modules: [
    // ...
    '@pinia/nuxt',
  ],
})

Upvotes: 1

Related Questions