An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
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
Was it helpful? Support me on Patreon
Original Link: https://dev.to/0shuvo0/vuejs-smart-login-redirect-3dng
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To