Sensanaty
Sensanaty

Reputation: 1106

Vue Router redirect users to a different homepage if they're already logged in

Running Vue 2.6.11 and Vue Router 3.2.0, authentication is handled via a Rails backend delivering JWTs to the Vue app. The JWTs are stored in LocalStorage once a user logs in.

I have 2 main pages on my app, a Homepage and a Dashboard. The homepage is basically just a landing page which is just explaining what the app is about + a sign in button, and my dashboard is where logged in users access the actual functionality of the app. What I'd like to do is have returning users be automatically redirected to the Dashboard upon visiting the root URL, since they won't be interested in looking at the homepage once they've already made an account.

What would be the proper way of handling this? I know I could just do a router.beforeEach to check for the JWT and then redirect it from there, but the problem is that that would also interfere with other pages, making them always redirect to the dashboard which I obviously don't want. The homepage is the one and only page that I want logged in users to skip seeing.

Upvotes: 0

Views: 951

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

You can still use beforeEach to do this. Just check if the route you're navigating to is the homepage:

router.beforeEach((to, from, next) => {
  if (to.name === 'Home' && isAuthenticated) {
    next({ name: 'Dashboard' })
  } else next()
})

Upvotes: 2

Related Questions