Nuxt3 - Issue with Accessing Environmental Variable in Pinia Store

I've encountered an issue while trying to access the BASE_URL from the environment in a Pinia store within Nuxt using runtimeConfig, resulting in a 500 Nuxt instance unavailable error.

Below is the error image link:

https://i.sstatic.net/hOZF7.png

Interestingly, manually setting the BASE_URL works fine, but accessing it from an environmental variable causes the error.

Here's the code snippet:

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
    }
  }
})

Answer №1

Yes, I have identified the issue.

The primary concern is that the useRuntimeConfig function is inaccessible from outside of a store.

For instance:

home-store.ts

/**
 * NOT RECOMMENDED - doesn't work outside the store
 */
const BASE_URL = useRuntimeConfig().public.api_url;

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

  actions: {
    async getHomePageData() {
      /**
       * RECOMMENDED - works inside the store
       */
      const BASE_URL = useRuntimeConfig().public.api_url;
      console.log('BASE_URL HERE:', BASE_URL);
      this.homePageData = await $fetch(`${BASE_URL}/products`);
    },
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to conceal a form field until a previous field has been completed?

Looking for a way to hide a form field until another field is properly completed? I have a divided registration form and want the second field to appear only when the first one is valid. Preferably using CSS3, with HTML5 and maybe some JavaScript if necess ...

Instructions for downloading a .zip file sent through a HTTP response (using an axios PUT request)

When the API responds, it should contain a data property with the .zip file I need. However, the format is unfamiliar to me. The format: https://i.sstatic.net/ruaVR.png I attempted to use .blob() as suggested in similar questions on Stackoverflow, but it ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Express JS: The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am encountering an issue with my API running on a server and the front-end client attempting to retrieve data from it. Previously, I successfully resolved the cross-domain problem, but now it seems like something has changed as I am receiving ...

Search for a DIV element within iMacro on a consistent basis

I recently started using iMacro and encountered an issue while recording a script that involved clicking on a pop-up when it appeared on the screen. The problem arose because the pop-up only appears when a new event is posted. Therefore, when I initially c ...

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

Trouble with serving CSS files using Express static directory

In my app.js file, I have the following code: app.use(express.static(path.join(__dirname, '../public'))); This code snippet is from my main layout page: <link rel="stylesheet" href="/css/styles.css"> Despite trying various combinations, ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

How can I place a custom text message in the top-right corner of the assetManager popup within a Vue component using CSS in GrapesJS?

I have created an assetManager popup where I am looking to incorporate a text message in the highlighted red line area on the right-hand side of the popup. https://i.sstatic.net/depuT.png Previously, I had hidden the "Add button" button and textbox. Now, ...

Using Observables to assign values received from API calls to each element during loop iterations

As I loop through using a foreach loop, I need to call functions that will make async API calls and return values to be rendered in the HTML. The first function getCurrentValue() will return the currentTemperatureRef which should then be assigned to recei ...

Tips for displaying the HTML content within the autocomplete box

My situation involves a text input and an HTML form where users can submit their name to retrieve information. I am using AJAX to display the usernames dynamically. <div class="hidesearch" id="search" style="width:"400px;"> <inp ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

Paused momentarily to allow user input

I am currently developing a new game where the player and enemies are stored inside objects with various properties. For example, each object includes: $player->health $player->attack (which represents attack power) Additionally, there is a PHP fun ...

Troubleshooting my Vue app: the mystery behind why I'm unable to utilize debugger or console.log

After setting up a new Vue app using Vue CLI, I encountered an issue where I am unable to utilize the debugger or console.log without triggering an error in the browser. Could anyone provide insights on why this is happening and how it can be resolved? ...

Can you explain why there is a discrepancy in the canvas coloration?

When I try to draw a line on my canvas with color "#ca5100", the actual color that appears is "#e4a77f". Why does this difference occur and how can I ensure that the correct color is set? var ctx = document.getElementById("mycanva").getContext("2d"); ct ...

What is the best way to transition all elements down while sliding a header up or down?

Is it possible to bring down the entire page when hovering over a header element using CSS, ensuring that the header overlaps nothing else on the page? If so, how can this be achieved? See an example of the header in action here: Thank you! ...

Strategies for spreading a mode to the composite component within VueJS

When it comes to the Vuetify text field component, there are numerous options available for customization. One idea is to create a custom text field component with predefined options such as icons, flat design, or boxed layout. However, I want to avoid man ...