We’re setting up a simple redirection for Vue.JS, React.JS and Angular. But you can also try to implement or make similar approach on Vanilla.Js and other JS frameworks or libraries.
Make sure to register this path on your routing system. Examples below.
<Switch>
<Route exact path="/login/r/:redirectionUrl">
<Login />
</Route>
</Switch>
const routes = [
{ path: '/login/r/:redirectionUrl', component: Login }
]
const routes: Routes = [
{ path: "login/r/:redirectionUrl", component: LoginComponent }
]
r
stands for redirection. I just made it simplified in our url path.
Alternatively, you can store the previous page path in localStorage
or sessionStorage
depending on your requirements.
I decided to put this simple javascript logic inside JWT token expiration validator. So when the JWT token is expired, then we redirect the user to the login page with that previous page attach to its url.
import jwt_decode from 'jwt-decode'
function checkIfJwtTokenExpired(){
const token = localStorage.getItem("token")
if(token){
const decodedToken = jwt_decode(token)
if(decodedToken.exp < new Date().getTime() / 1000){
window.location.href = `/login/r/${window.location.pathname}`
}
}
}
If you’re using other session validator, then it’s fine. The main highlight of that code is our
window.location.href = `/login/r/${window.location.pathname}`
In this step, let’s assume that we’re at the login page with attached URL of the previous page. For example,
let redirectURLPath = window.location.pathname
// slice first 8 characters which is /login/r
redirectURLPath = redirectURLPath.slice(8)
// then we check if it's successfully login or not. (In depends on what logic you have)
if(successAuth || validAccess){
// we get the value of redirectURLPath and redirect it to the page. In our example, it's the products page.
// for Vue.JS
this.$router.push({path: redirectURLPath})
// for React.JS
<Redirect to={ { pathname: redirectURLPath } } />
// for Angular
this.router.navigate([redirectURLPath]) or this.router.navigateByUrl(redirectURLPath);
}
That’s it. I hope you find this blog helpful.
If you have some questions or comments, please drop it below 👇 :)
