Packy
Packy

Reputation: 3573

Vue / Vuex State Management best practice for auth

Not sure if this is the right place for this question since its more of "best practice" and not technical per say but I am new to building a SPA with Vue. From what I have seen so far Vuex is a good tool to handle the state of cross component application data. What I currently have is working good for my user, logged in status and side-drawer menu state (open / closed), but before I go down a rabbit hole I wanted to get some community input on my store.js setup. Auth uses JWT.

Is it good practice to use store to handle login, logout and the user info? All the tutorials I have found are not to real world (using it for a counter or something).

If this is not the appropriate place to ask this before down voting, please let me know the right Stack Exchange site to ask.

import Vuex from 'vuex';


export const store = new Vuex.Store({

    state:{
        isLoggedIn: !!localStorage.getItem("jwt_token"),
        user: localStorage.getItem("user")? JSON.parse( localStorage.getItem("user") ) : {},
        showDrawer: false
    },

    mutations:{

        login: state =>{

            state.isLoggedIn = true;

            state.user = JSON.parse( localStorage.getItem("user") );

            //set the Axios header so we pass Auth on the API
            window.axios.defaults.headers.common['Authorization'] = localStorage.getItem("jwt_token");

        }, 

        logout: state =>{

            localStorage.setItem("jwt_token", '');

            localStorage.setItem("user", '');

            state.isLoggedIn = false;

            state.user = {};

            state.showDrawer = false;
        },

        openDrawer: state =>{
            state.showDrawer = true;
        },

        closeDrawer: state =>{
            state.showDrawer = false;
        }
    },

})

Upvotes: 1

Views: 2776

Answers (1)

Hi I am using this pattern.

https://blog.sqreen.io/authentication-best-practices-vue/

It achieves:

  • Isolated authentication logic from the app and other libs.

  • No need to explicitly pass tokens to every API call.

  • Handle all unauthenticated API calls

  • Has auto authentication

  • Has restricted routes access

  • Separation of concerns

  • Avoid side effects

  • Action dispatch can return promises

    Hope it helps

Upvotes: 2

Related Questions