Redirect to requested page after login using vue-router

Schwesi picture Schwesi · Aug 24, 2017 · Viewed 53.5k times · Source

In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redirected to the login component.

If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.

How can I achieve this using vue-router?


My code without redirect after login

router.beforeEach(
    (to, from, next) => {
        if(to.matched.some(record => record.meta.forVisitors)) {
            next()
        } else if(to.matched.some(record => record.meta.forAuth)) {
            if(!Vue.auth.isAuthenticated()) {
                next({
                    path: '/login'
                    // Redirect to original path if specified
                })
            } else {
                next()
            }
        } else {
            next()
        }
    }        
)



My login function in my login component

login() {
    var data = {
        client_id: 2,
        client_secret: '**************',
        grant_type: 'password',
        username: this.email,
        password: this.password
    }
    // send data
    this.$http.post('oauth/token', data)
         .then(response => {
             // authenticate the user
             this.$auth.setToken(response.body.access_token,
             response.body.expires_in + Date.now())
             // redirect to route after successful login
             this.$router.push('/')
          })



I would be very thankful for any kind of help!

Answer

V. Sambor picture V. Sambor · Jan 16, 2018

This can be achieved by adding the redirect path in the route as a query parameter.

Then when you login, you have to check if the redirect parameter is set:
- if IS set redirect to the path found in param
- if is NOT set you can fallback on root.


Put an action to your link for example:

onLinkClicked() {
  if(!isAuthenticated) {
    // If not authenticated, add a path where to redirect after login.
    this.$router.push({ name: 'login', query: { redirect: '/path' } });
  }
}

The login submit action

submitForm() {
  AuthService.login(this.credentials)
    .then(() => this.$router.push(this.$route.query.redirect || '/'))
    .catch(error => { /*handle errors*/ })
}

Hope it helps.