Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 17, 2021 12:52 pm GMT

Vue.JS Smart Login Redirect

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()})

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 }    })}

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>

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('/')    }}

Make sure to checkout my other articles

.ltag__user__id__728097 .follow-action-button { background-color: #000000 !important; color: #ffffff !important; border-color: #000000 !important; }
0shuvo0 image

Was it helpful? Support me on Patreon

Patreon Logo


Original Link: https://dev.to/0shuvo0/vuejs-smart-login-redirect-3dng

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To