Maintain user authentication status in Vuex after page refresh

Hello, I have implemented a setup using Vuex and Laravel sanctum for user authentication. Below is the code snippet from my Vuex file auth.js:

import axios from 'axios'

export default {

    namespaced: true,

    state:{
        authenticated: false,
        user: null
    },

    getters:{
        authenticated (state) {
            return state.authenticated
        },

         user (state) {
            return state.user
        }
    },

    mutations:{
        SET_AUTHENTICATED(state, value){
            state.authenticated = value
        },

        SET_USER(state, data){
            state.user = data
        }
     },

    actions:{
        async login ({commit}, credentials){
         await axios.get('/sanctum/csrf-cookie')
          await axios.post('/api/login', credentials).then(response => {
                commit('SET_AUTHENTICATED', true)
                commit('SET_USER', response.data)
            }).catch(() => {
                commit('SET_AUTHENTICATED', false)
                commit('SET_USER', null)
            })

        },


    }

}

Although the authentication process works fine, the issue arises when the page is refreshed as the authentication status resets to false. Can someone guide me on how to retain the authentication status as true if the user is already authenticated?

Answer №1

When it comes to storing data, there are two main choices: cookies or local storage. These options are commonly utilized, with frameworks like Nuxt Auth making use of them.

If you're looking for a simple way to persist the store, consider using vuex-persist. Check out the beginner's guide here.

Answer №2

If your API returns a token, you have the option to save it in local storage.

state: {
    authenticated: false,
    user: null,
    token: localStorage.getItem('token') || '',
},
actions:{
    await axios.post('/api/login', credentials).then(response => {
        const token = response.data.token
        localStorage.setItem('token', token)
    })
}

You can manage an expired token with the help of Axios interceptors:

created () {
    this.$axios.interceptors.response.use(undefined, function (err) {
        return new Promise(function (resolve, reject) {
        if (err.status === 401) {
          this.$store.dispatch(logout)
        }
        throw err;
      });
    });
}

Vuex logout action

logout({commit}){
  return new Promise((resolve, reject) => {
    commit('logout')
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
    resolve()
  })
}

Answer №3

@design-studio-pj. I believe it is risky to save a token in LocalStorage as it contains user credentials. From my research on LocalStorage, it is strongly advised not to utilize it for storing login information or other highly sensitive data.

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

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Combining text and hyperlinks within React/TypeScript variables for dynamic content

Seeking a way to combine a string and a link within an attribute of one variable: const News = [ { headline: 'some headline', text: "some text" + <a href='url'> click me </a>, }, ]; When I displa ...

Exploring the world of JavaScript popups

I'm having an issue with implementing a JavaScript popup on my website. I've created a jsfiddle demo, which can be found here: http://jsfiddle.net/68vGZ/ Here is the code snippet: HTML <div id="header-links"> <button id="aboutinfo" ...

nodemon breaks down frequently while anticipating changes in files

After cloning a project that I finished 2 months ago, I am facing an issue where nodemon won't run. Despite trying to close npm using task manager on Windows and running it again, the error persists. I am also utilizing MongoDB as my database. If any ...

Any ideas on how I can enable rotation of SVG images within a Bootstrap 4 Accordion card with just a click?

I'm working on a Bootstrap 4 accordion card that has an SVG arrow image in each header. I am trying to make the arrow rotate 180 degrees when the header is open, and return to its initial state when it is closed or another header is opened. Currently, ...

applying classes conditionally in Vue.js

Attempting to toggle a class of an element in Vue.js, which I am currently learning. The goal is for the disabled class to be applied when included is not true. A function called toggleClass has been created, but it doesn't appear to be working. Li ...

Vue Navigation Guard automatically redirects users when trying to access a URL directly

I'm currently setting up Vue Navigation Guards. A guard I have in place redirects users from the Index component to the Dashboard component if they are authenticated with Firebase Auth. The redirect works perfectly when navigating to the Index page t ...

Scroll Reveal in Vue.js: Implementing a Dynamic Footer

Trying to implement a footer with scroll reveal functionality similar to this example: https://codepen.io/nickcil/pen/Eoqiv #footer { height: 200px; position: fixed; left: 0; bottom: 0; z-index: -1; } While the implementation is straightforward ...

What is the best way to insert additional divs into a box div that contains tabs?

My current challenge is as follows: On a webpage, I have a box with jQuery tabs labeled "Enter" and "About" designed to switch the content displayed within the box. UPDATE: The jQuery script in use is shown below: <script type="text/javascript"> ...

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

When state updates in React, the component will rerender without affecting its style

There seems to be a minor oversight on my part. The issue arises in the parent component where I maintain a state of selected items, which are added from the child component. The background color of the child component changes when an item is selected. Ad ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Need help transmitting form data via Axios in Vue.js and Node.js?

Exploring Api.Js import axios from 'axios' export default () => { return axios.create({ baseURL: "http://localhost:4040", credentials: true }) } Discussing PageService.js import Api from "@/services/Api"; expo ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

Intersecting Rays and Positioning Spheres with three.js

I have a scenario where ray intersection is functioning properly with tube geometry. Upon ray intersection, a small red sphere and a tooltip appear next to the cursor. The image below shows the scene without a header: When I include a header using a div e ...

The responsive class seems to be malfunctioning within the Laravel 5.3 framework

I have a project that involves Laravel and Vue.js. In my Laravel project, I am importing Bootstrap CSS using the following line: // Bootstrap @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; This import is done in the app.scss file. ...

Increase the state by 1 every interval, unless the current state is equal to or greater than the maximum value by using

How can I create an animation effect by incrementing the current state by 1 until it matches a specified maxValue? The interval for this animation is set using setInterval, but I want it to stop when the state reaches the maximum value. Currently, when th ...

Is it time to ditch Internet Explorer for EDGE?

Have you ever noticed that when attempting to access the stackoverflow website on Internet Explorer, the tab mysteriously closes and Microsoft Edge opens with stackoverflow loaded? What is the secret behind this strange phenomenon on stackoverflow's ...

Sending query parameters from one URL to another using jQuery

Greetings! I have implemented a load more feature using a script that loads additional content on the same page when the 'Load More' button is clicked. Below is the script: <script type="text/javascript"> var track_page = 1; load_c ...