Loading...

How to add routing authentication in vue js

Image

In this tutorial, we will learn how to add routing authentication in Vue.js. Protecting routes ensures that only authenticated users can access certain parts of your application. We will use Vue Router's navigation guards to achieve this. By the end of this guide, you will have a functional login system with protected routes.

First, install Vue Router if you haven't already:

npm install vue-router

Step 1: Set Up Vue Router

Create a file named router.js (or similar) and configure your routes in router.js file.

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'login',
    component: () => import('../pages/login.vue'),


	//check if user is already logged in than don't open the login page
    beforeEnter: (to, from, next) => {
      const userData = JSON.parse(localStorage.getItem('userData'))
      if (userData) {
        next('/home')
      } else {
        next()
      }
    },
  },
  
  //if the user is logged in than only he can go inside this otherwise he will be redirect to login page
   {
    path: '/website-inner',
    name: 'website-inner',
    component: () => import('../pages/user_layouts/InnerLayout.vue'),
    redirect: '/website-inner',
    beforeEnter: (to, from, next) => {
      
      const userData = JSON.parse(localStorage.getItem('userData'))

      if (!userData){
        next('/')
      }else{
        next()
      }
    },
    children: [
     	{
        	path: '/home',
        	name: 'home',
        	component: () => import('../pages/user_designs/Home.vue'),
      	},
       ]
     }
}
  
const router = createRouter({
  history: createWebHistory('/'),
  routes,
})

export default router

I have already teach how to to login functionality in my last block you can check that here.

In Order to do the logout  functionality in VUE Js the code is below.

<script setup>
import axios from 'axios';

//gey user details or token from localstorage
const getUserDetails = JSON.parse(localStorage.getItem('user_details'));

//logout function
const logoutUser = ()=>{
	axios.post('https://example.log/api/logout' , 	{user_id:getUserDetails.user_id}).then((res)=>{
	const {status , message} =  res.data;
	
		if(status === true){
			localStorage.clear();
			window.location.reload();
		}else{
		    alert(message)
		}	
	})
}
	
</script>

<template>
	<button @click="logoutUser">logout</button>
</template>

0 Comments

Leave a comment