hidar
hidar

Reputation: 5939

How to give access to page in Vue.js only if a user is logged in / localStorage exists?

I currently have a simple Vue.js application, I am using vue-router like this. index.html

<p>
  <router-link to="/" exact> Home </router-link>
  <router-link to="/about"> About </router-link>
  <router-link to="/contact"> Contact </router-link>
  <router-link to="/login"> Login </router-link>
  <router-link to="/register"> Register </router-link>
</p>
<router-view></router-view>

And I have this in my /routes.js

import VueRouter from 'vue-router';

let routes = [
  {
    path: '/',
    component: require('./components/Home.vue')
  },
  {
    path: '/about',
    component: require('./components/About.vue')
  },
  {
    path: '/login',
    component: require('./components/Login.vue')
  },
  {
    path: '/register',
    component: require('./components/Register.vue')
  }
];

export default new VueRouter({
  mode: 'history',
  routes
});

I have index.js file which initialized the app, I think I should do something within my created(){} module but I am not sure how it is done.

I can set/unset sessions, all I need to know is how to give access to a page only if this session exists.

Upvotes: 2

Views: 6583

Answers (1)

Theus
Theus

Reputation: 83

You can use Navigation Guards to verify some data before transition of page conclude.


It depends. With Navigation Guards you can verify if a user is logged before a transition of pages. Eg:

If user is on /home and he wants go to /dashboard, before user enter on /dashboard, a Navigation Guard will verify if user is logged. If yes, continue to /dashboard, if not, redirect to /login.

Internally, you can set a data of user when he do the login. Has many ways to do this thing but you must consider the security of system, etc.

This other question has a simple example to verify a user logged and this article shows how to do this verification using Vuex, being more intesting.

Upvotes: 2

Related Questions