Vue.JS Smart Login Redirect

Shuvo - Nov 17 '21 - - Dev Community

Imagine someone scrolling through a social media and he finds a link to an interesting article on your website. So he clicks on it to see. But he was not logged in so your website redirected him to the login page. But after logging in he was redirected to home page. So now he have to navigate back to that article page manually. But this is not a good UX.
After logging in your website should have redirected him back to the page he came from. Lets see how to do that.
Okay in our router guards instead of just redirecting the user like this



const isLoggedIn = () => {
    return localStorage.getItem('token')
}

const protectedRoutes = [
    "Home",
    "About",
    "Product"
]
router.beforeEach((to, from, next) => {
    const isProtected = protectedRoutes.includes(to.name)
    if(isProtected && !isLoggedIn()){
        next({
            path: '/login'
        })
    }else next()
})


Enter fullscreen mode Exit fullscreen mode

We will redirect the user to the login page along with the page he was on as a query parameter.



if(isProtected && !isLoggedIn()){
    next({
        path: '/login',
        query: { redirect: to.fullPath }
    })
}


Enter fullscreen mode Exit fullscreen mode

And now the the login page after the users logs in instead of just redirecting him to the home page like this



<template>
    <button @click="login">Login</button>
</template>

<script>
export default {
    methods: {
        login() {
            /* Do Stuff */
            localStorage.setItem('token', '12345')
            this.$router.push({ path: "/" })
        }
    }
}
</script>


Enter fullscreen mode Exit fullscreen mode

We will see if we have the redirect query parameter, if we do we can use it to send user back to the page he came from



login() {
    /* Do Stuff */
    localStorage.setItem('token', '12345')
    if(this.$route.query.redirect) {
        this.$router.push(this.$route.query.redirect)
    }else{
        this.$router.push('/')
    }
}


Enter fullscreen mode Exit fullscreen mode

Make sure to checkout my other articles

Was it helpful? Support me on Patreon

Patreon Logo

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .