Redirect to login page in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to set up your router so that if a user is not authenticated it redirects to /login page.

This is a very common case to most of the single page applications with authentication.

We’ll be using Vuex in this example. If you’re not using Vuex along with Vue you should consider using it. It was created by the mighty Evan You, a guy who created Vue.js, and it makes your life easier.

Vue.js redirect to /login example

beforeCreate () {
  if (this.$store.state.isLogged) {
    this.$router.push({ name: 'login' })
  }
}

We can use beforeCreated() hook to redirect unauthenticated user to /login page. Remember the Vue.js lifecycle hooks?


Hi, I'm Renat 👋

 


In the example above we check if the user’s current state is set to isLogged: true, if false we redirect a user to /login page.

This is how the Vuex getter for isLogged looks like:

isLogged: state => {
  return state.isLogged
}

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/redirect-to-login-vue-js

PS: Make sure you check other Vue.js tutorials, e.g. how to display a random image in Vue.js.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment