Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to retain the information.

Here is the logic on my login page for sending the information, fetching the token from the backend, and attempting to commit it to my mutation:

async submitForm() {
    const response = await axios.post(
        'http://localhost:3000/api/user/login',
        {
            email: this.email,
            password: this.password,
        }
    );

    const responseData = await response.data;

    const expiresIn = +responseData.expiresIn * 5000;
    const expirationDate = new Date().getTime() + expiresIn;

    localStorage.setItem('token', responseData.token);
    localStorage.setItem('userId', responseData.userId);
    localStorage.setItem('email', responseData.email);
    localStorage.setItem('tokenExpiration', expirationDate);
    this.$cookies.set('token', responseData.token);
    this.$cookies.set('userId', responseData.userId);
    this.$cookies.set('email', responseData.email);
    this.$cookies.set('tokenExpiration', expirationDate);

    this.$store.commit('setUser', {
        token: responseData.token,
        userId: responseData.userId,
    });
},

This is how my store information is set up:

Index.js

import mutations from './mutations.js';
import getters from './getters.js';

export default {
    state() {
        return {
            userId: null,
            token: null,
            didAutoLogout: false,
        };
    },
    mutations,
    getters,
};

mutations.js

export default {
    setUser(state, payload) {
        state.token = payload.token;
        state.userId = payload.userId;
        state.didAutoLogout = false;
    },
    setAutoLogout(state) {
        state.didAutoLogout = true;
    },
};

getters.js

export default {
    userId(state) {
        return state.userId;
    },
    token(state) {
        return state.token;
    },
    isAuthenticated(state) {
        return !!state.token;
    },
    didAutoLogout(state) {
        return state.didAutoLogout;
    },
};

The isAuthenticated function is called in my default layout as shown below:

export default {
    computed: {
        isAuthenticated() {
            return this.$store.getters.isAuthenticated;
        },
    },
};

I also attempted using Nuxt auth with cookie:

auth: {
    strategies: {
        cookie: {
            token: {
                property: 'token',
                global: true,
            },
        },
    },
},

and local:

auth: {
    strategies: {
        local: {
            token: {
                property: 'token',
                global: true,
            },
        },
    },
},

Answer №1

When performing a hard refresh, a new instance of the app is created by default, resulting in the re-initialization of the store to its original state.

Nuxt, being a server-side framework for Vue, offers a solution which involves using Cookies to maintain the state within your store.

LATEST UPDATE

Utilize the cookie-universal-nuxt module to have access to cookies both on the client and server side.

To ensure that your store is reinitialized with the cookie values on the server side upon each refresh, add this method to your store actions. (This method will run on the server side during the initial stage of the app)

export default {
  nuxtServerInit({ commit }, { req, app }) {
    const token = app.$cookies.get('token')
    const userId = app.$cookies.get('userId')
    const payload = {
        token,
        userId
    }
    commit('setUser', payload)
  },
};

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

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Is there a way to individually apply loading to only the button that has been clicked in vuejs?

One problem I am facing is that when I click a specific button in a table, all buttons end up in loading mode. The table loops and displays data from an API, with a button embedded in each row. Upon clicking the button, it should send the ID of the clicked ...

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

Issue with the table not being displayed when any of the submitted fields are left empty

After submitting the first field, I receive the second value, and after submitting the second field, I get the third value. I have a group of three fields that are interconnected. <?php $courtname=''; if(!empty($_POST['court_ ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Implement pagination within a div populated by a v-for loop in Vue.js

I'm struggling to implement pagination within my v-for loop in the div. The data is displayed correctly, but I can't seem to get the pagination working. Can anyone suggest a suitable pagination method for this task? I want to display only 5 items ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Issue with v-html in Vue rendering plain text instead of HTML

Welcome to the simplified version of my application: const app = Vue.createApp({ }); app.component('list', { props: { model: { type: Object } }, template: `<div v-for="widget in model.widgets"> {{ widget.n ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

Troubleshooting [Vue Router warning]: Ignoring invalid parameter(s) "id" during navigation

Incorporating VueJS 3.3 along with Vue Router v4, my route structure is as follows: https://i.stack.imgur.com/ExZ9N.jpg Despite navigating properly to the intended URL http://localhost:5173/koin/document-sets/177/comments, Vue continuously throws an erro ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Developing a dynamic input field module in Vue.js

I am currently working on a reusable component for input fields that allows me to define them easily within one component tag using props. My goal is to make the component versatile enough to be used as text, date, password, number, etc., based on a condit ...

Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined Check out the code snippet below: <template> ... </template> <style lang="scss"> ... </style> <script> export default { ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

What steps can be taken to eliminate the useSearchParams() and Suspense deployment error?

I'm encountering an issue where ⨯ useSearchParams() needs to be enclosed within a suspense boundary on the page "/PaymentPage". More information can be found at: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout Although I have wra ...

At times, JavaScript interacts with Selenium to click on the login button before I have the chance

I have a challenge while attempting to log in to Twitter using Selenium webdriver, here is the code I am working with: const {Builder, By} = require("selenium-webdriver"); (async function example() { let driver = await new Builder().forBrowser(' ...