user3052526
user3052526

Reputation: 681

Redirect If Authenticated NodeJS

I am using the following tech

i store the x-access-token in the localstorage.

When the user visits the site www.example.com a vuejs component does the following

Verifies if the user is logged in by calling an authentication endpoint If verified, it redirects to www.example.com/controlpanel

Ofcourse the problem is it takes a while for the vuejs component to load and therefore the page loads and later is redirected.

Is there a way of handling the above scenario in a cleaner way. Using ngnix even?

Thanks

Upvotes: 1

Views: 141

Answers (1)

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

In the component which is rendered on the visit to homepage(root route /) add a beforeRouteEnter() navigation guard as follows:

//in root route component options

beforeRouteEnter(to, from, next){
    myAjax.get('/auth').then((res) => {
        if(res.data.user){
            //user logged in
            next('/controlpanel');
        }else{
            next('/');
        }
    });
}

this guard is called before the route component is rendered and only gets confirmed and rendered if you invoke next()

keep in mind you will not have access to the compnents's vue instance as the component is not created yet

to get acceess to t vue instance inside beforeRouteEnter() do this:

beforeRouteEnter(to, from, next){
    next(vm => {
        //acess the component's instance using vm
    }
}   

For more info check out In-Component Guards

Upvotes: 1

Related Questions