After restarting, Nuxt 3 runtime configuration values do not get updated with environment variables

Encountered a challenge with updating variables in runtimeConfig that rely on environment variables.

When the application is built with values from the .env file like:

API_URL=localhost:3000

The console displays localhost:3000.

However, upon stopping the application, modifying the value in the .env file to:

API_URL=localhost:1234

And restarting the application, the console still shows localhost:3000.

Why didn't the runtimeConfig values update? This functionality worked flawlessly in Nuxt 2 but appears to be malfunctioning in Nuxt 3.

.env

API_URL=localhost:3000

nuxt.config.js

import svgLoader from 'vite-svg-loader';

const APP_HOST = process.env.API_URL
const BASE_URL = `https://${APP_HOST}`;

export default defineNuxtConfig({
    devtools: {
        enabled: true,
    },
    telemetry: false,
    test: true,
    app: {
        baseURL: '/fe',
    },
    build: {
        transpile: ['primevue'],
    },
    css: [
        '@@/assets/scss/base.scss',
    ],
    vite: {
        plugins: [
            svgLoader({
                defaultImport: 'component',
            }),
        ],
    },
    modules: [
        '@nuxtjs/eslint-module',
        // '@nuxtjs/stylelint-module',
        '@vueuse/nuxt',
        '@pinia/nuxt',
        '@bootstrap-vue-next/nuxt',
        // 'pinia-plugin-persistedstate',
    ],
    imports: {
        dirs: ['./const', './const/paths'],
    },
    components: [
        {
            path: './components',
            pathPrefix: false,
            extensions: ['.vue'],
        },
    ],
    runtimeConfig: {
        public: {
            http: {
                baseURL: BASE_URL,
            },
        },
    },
});

Login.vue

<template>
    <div>LOGIN</div>
</template>

<script lang="ts" setup>
const runtimeConfig = useRuntimeConfig();
const baseURL = runtimeConfig.public.http.baseURL;


onMounted(() => {
    console.log('runtimeConfig', baseURL);
    console.log('runtimeConfig', runtimeConfig);
});
</script>

Answer №1

To update the key in your .env configuration file, use the following:

.env

NUXT_PUBLIC_HTTP_BASE_URL=https://localhost:3000

nuxt.config.ts

runtimeConfig: {
   public:  
       http: {
          baseURL: 'https://localhost:3000',
       },
   },
},

You can also explore how the runtimeConfig feature functions in Nuxt 3 here

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

Are There Data Racing Issues in JavaScript?

Imagine executing the following code snippet. let score = 0; for (let i = 0; i < some_length; i++) { asyncFunction(i, function() { score++; }); // incrementing callback function } The code above may potentially lead to a data race issue where two ...

Securing Azure B2C user access with Auth Flow using PKCE, MSAL v2, Vue.js, & Azure Functions

Our application utilizes Vue.js, Azure B2C Tenant, and Azure Functions (C#) to authenticate users. We implement the Auth Flow with PKCE and utilize the MSAL v2 library on the front-end, specifically the npm package @azure/msal-browser for MSAL. The challe ...

Show a visual representation when Blob is retrieved from an API call

Currently, I am working on a Vue app that integrates with the Microsoft Graph API and SDK for authentication at the front end, along with using various features of the API like displaying emails, OneDrive files, etc. One specific challenge I am facing is ...

"Looking to transfer an array of object properties in a Vue.js application? Let's explore

component: To-Do List: <template> <ol> <li v-for="toDo in toDos" :key="toDo.id">{{ toDo.text }}</li> </ol> </template> <script> export default { name: "ToDoList", props: { toDos: Array }, ...

Does the execution of node.js event handlers occur when the calling stack is clear?

My belief that code related to node.js events is asynchronous was challenged when I came across the following example: var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('foo', function () ...

What is the best way to combine two objects in AngularJS?

https://i.sstatic.net/qr5Bb.png If you have two JSON objects that need to be merged while removing duplicate properties, what approach would you take? ...

Creating a custom loading page in Next.js 13: A step-by-step guide

Hello, I am currently working on implementing a loading page for my website to enhance the user experience during a longer loading time. I have created a simple functional component that displays a loading message and imported it into my layout.jsx file in ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

Guide to implementing PCF (SOFT) shadows with three.js

Is it possible to apply the PCF (SOFT) shadow type, like the one found in the Three.js online editor, to your renderer using javascript code? https://i.sstatic.net/x0QmH.png ...

Automated Form Submission: A Guide to Automatically Sending the Form After Captcha Verification

I'm looking to incorporate ReCaptcha into my website in order to display additional data. My goal is to have the form automatically submitted once the ReCaptcha has been completed, eliminating the need for an extra submit button. However, I've en ...

What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods? async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> { //log getAllActiveRooms return this.i.knex('users_rooms') .transacting(ctx ...

Error occurs in production environment in Vite 2 when the ref element is undefined while using the Composition API

While working with Vue3 and the composition API, I encountered an issue where the ref element remains undefined after building my project. I tried reproducing the problem and it seems like I might have used it incorrectly, but the reason behind this behav ...

Modify/Adjust/Move the image uploaded by the user in VueJS before transferring it to an aws s3 bucket

Can you resize images in vuejs using vanilla js? I've managed to upload an image and send it to my s3 bucket using vue, but I'm struggling to figure out how to transform an image within vuejs and display it. Document.querySelector doesn't se ...

Sending data from PHP to a text file upon clicking a button

I have been struggling with AJAX and despite my efforts to research on Stack Overflow and other online resources, I still can't get it to work. Any help would be greatly appreciated. My issue involves a formatted JSON file that I am able to parse usi ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

Using Jquery to access the grandparent element

When I have code similar to what is shown below, an element contains within 3 layers: <span class="dropdown test1"> <span class="test2" type="button" data-toggle="dropdown">hello</span> <ul class="dropdown-menu test3" style="m ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

Peculiar redirection encountered while handling a form with checkbox option

When I try to submit the form in Chrome, the PHP file does not get called and I am redirected to another HTML page. However, in Firefox, when I select three checkboxes, it redirects me to that same HTML page as in Chrome. I even tried using radio buttons i ...

Vuetify's v-text-field not properly aligning text to the center

The alignment of the text in v-text-field is causing issues for me, as I am unable to center it. Despite attempting various solutions, I have not been successful. 1. <v-text-field type="number" class="mr-2 text-center"></v-te ...