Search code examples
javascriptvue.jsruntime-errornuxt3.js

Nuxt3 - Environmental Variable not access in Pinia Store


I have one problem. I'm actually trying to access BASE_URL from env in Pinia store through nuxt runtimeConfig it gives an error 500 nuxt instance unavailable

Here's the error image

enter image description here

One thing I want to point out is when I hard coded BASE_URL it works fine but when I trying to access BASE_URL from environmental variable It give an error.

Here's my code

Pinia Store

// Pinia Store for Home Page
import { useRuntimeConfig } from '#app'

const BASE_URL = useRuntimeConfig().public.api_url

export const useHomeStore = defineStore('home-store', {
  state: () => ({
    homePageData: {}
  }),

  actions: {
    async getHomePageData() {
      this.homePageData = await $fetch(`${BASE_URL}/products`)
    }
  }
})

Nuxt Config

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      api_url: process.env.BASE_URL
    }
  }
})

Solution

  • Ok, it seems I understand the problem.

    The main matter is that you don't have access to useRuntimeConfig function from outside a store.

    The example:

    home-store.ts

    /**
     * BAD - outside store, not working
     */
    const BASE_URL = useRuntimeConfig().public.api_url;
    
    export const useHomeStore = defineStore('home-store', {
      state: () => ({
        homePageData: {},
      }),
    
      actions: {
        async getHomePageData() {
          /**
           * GOOD - inside store
           */
          const BASE_URL = useRuntimeConfig().public.api_url;
          console.log('BASE_URL HERE:', BASE_URL);
          this.homePageData = await $fetch(`${BASE_URL}/products`);
        },
      },
    });