Redirect to login page in Vue.js

Renat Galyamov
2 min readJun 26, 2019

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 the unauthenticated user to /login page. Remember the Vue.js lifecycle hooks?

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 or Top 5 CSS frameworks for your Vue.js project (2019).

Originally published at https://renatello.com on June 26, 2019.

--

--

Renat Galyamov

I’m a founder of Wonder.store and MED24.KZ. A front-end developer with over 9 years of experience building businesses.