Managing login API tokens in Vue JS

I have implemented a custom Login component in my Vue project:

var Login = Vue.extend({
    template: '#auth',
    data: function () {
        return {username: '',password: '',errorMessage:''};
    },
    methods : {
        login: function (e) {
            var _this = this;
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:_this.username,
                    password: _this.password
                },
                success: function (data) {
                    // Should I store the token in a global variable??
                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        }
    }
});

After successful authentication, the login API returns a token string. Would it be better to store this token in a global variable or locally using localStorage? Also, is there a filter available that can help check if the user is logged in, allowing for appropriate redirection?

Answer №1

Utilizing VUEX is the optimal approach: a comprehensive state management system designed for Vue.

Within your vuex store.js file, you can outline the user's state like so:

const store = new Vuex.Store({ 
    state: { 
        user: {
            userName:'',
            loggedInStatus: true,
            authToken: ''
        }
    }, 
    mutations: { 
        addWebToken: function(state, webToken){
            state.user.authToken = webToken;
        },
        removeWebToken: function(state){
            state.user.authToken = '';
        }
    },
    actions: {
        login: function(context, userInput){
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:userInput.username,
                    password: userInput.password
                },
                success: function (data) {

                context.commit('addWebToken', webToken);

                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        },
        logout: function(context){
            //logout functionality
            context.commit('removeWebToken');
        }
    }

})

In your component > methods > login(), you can invoke the login action defined in your vuex store as follows:

var Login = Vue.extend({
        template: '#auth',
        data: function () {
            return {username: '',password: '',errorMessage:''};
        },
        methods : {
            login: function () {
                this.$store.dispatch('login', {username: this.username, ppassword: password});
            },
            logout: function(){
                this.$store.dispatch('logout');
            }
        }
    });

The benefits of this implementation :

  • You have a central state to manage all user information

  • You can preserve the state locally or as cookies using vuex- persisted state. This method stores the user's state, including the web token, even when the page is refreshed, allowing the user to remain logged in.

const store = new Store({
        // ... 
        plugins: [ createPersistedState({
            getState: (key) => Cookies.getJSON(key),
            setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
        }) ]
    })

To implement vuex persisted state plugin and utilize jscookies library to save the user's state in cookies or local storage, refer to the vuex-persistedstate documentation.

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

One-touch dial feature for mobile-friendly website

Currently working on a single page responsive website and looking for guidance on inserting a quick call button that will only be visible when accessed on mobile phones, while remaining hidden on desktops and tablets. Your assistance is greatly valued. Th ...

The overflow hidden property does not seem to be effective when used in conjunction with parallax

The issue arises when I attempt to use the overflow hidden property in combination with parallax scrolling. Although everything seems to be working correctly with JavaScript for parallax scrolling, setting the overflow to hidden does not contain the image ...

What is causing the malfunction in this code? (Regarding the key and value variable objects)

var elements = []; var attribute1 = $(index).attr('class'); //or any string var attribute2 = $(index).html(); //or any string elements.push({ attribute1: attribute2 }); When I run this code, the output I receive is: this Why am I unable to set ...

Differences Between Using Array.push() and Literal (Bracket) Notation in JavaScript

I am looking at this specific answer. What is the reason behind Code Snippet 2 not producing the same result as Code Snippet 1? Code Snippet 1: var firstEvents = events.reduce(function(ar, e) { var id = e.getId(); if (e.isRecurringEvent() && ...

Sending form input values to JavaScript

Struggling to design a webpage featuring one text box and a button that, when clicked, sends the value to Javascript for further processing? After spending significant time troubleshooting, I'm unsure of what's causing the issue. Below are both t ...

Utilize form binding with Vue router's push method

I am currently developing a filtering component for a grid system. This component includes various fields where user inputs are stored in a model. When the user fills out the form and submits it, I have the following code for the submission process: method ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

Guide to creating a new element using jQuery

Question regarding JQuery and a Dropzone plugin. Here is the HTML code: <form action="/file-upload" class="dropzone"> <div class="fallback"> <input name="file" type="file" multiple /> </div> </form> Desired styling ...

Ways to include Bootstrap Tooltips on an input field that has the type of "file"

I attempted the code below: <input type="file" name="file" id="fileField" data-toggle="tooltip" data-placement="bottom"/> <script> $(document).ready(function() { $('[data-toggle="tooltip"]').tooltip(); }); </script> ...

Time-sensitive Meteor Collections that automatically expire

I was thinking of using a Collection for this. It's crucial that the data gets cleared after a certain period of time, though. Is there a way to set an expiration date for a Meteor Collection? I need to empty the collection 30 seconds after making m ...

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

What is preventing the Date Picker in Selenium from accepting attribute values when using JavaScript for the Spice Jet application?

My implementation of JavaScript for the Date picker in Selenium is running successfully, however, the date is not being selected in the date picker. public class SpicJetBooking { static WebDriver driver; public static void main(String[] args) t ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

text shaped into a curve within a container

$().ready(function() { $('#demo1').circleType({fitText:true, radius: 180}); }); $().ready(function() { $('#example').arctext({radius: 250}); }); <script type="text/javascript" src="http://ajax.googleapis.com/ ...

Limiting the amount of blogs shown on a single page can be achieved with Yii 1 and PHP

I have successfully implemented a feature to display blogs on one page. However, I now want to modify it so that only 5 blogs are shown per page and the user can click on a "next page" button to view the next set of 5 blogs. Here is the code snippet from ...

Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

When there is a duplicate route in Vue-router and the back-end, which one will handle the request first - Vue.js or the back-end?

Picture this scenario: I have a domain named test.com serving a Single Page Application (SPA) with a route /home, and there is also a back-end serving the SPA which has a route called /home as well. Who will respond first if I type test.com/home in my br ...

Arrangement of elements in MongoDB

In my application, there is a list of games, each with a specific position that determines the order in which they are displayed to users (e.g. 1, 2, 3...). Currently, I am using MongoDB to store all the game data. Let's say I have a game with positi ...

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...