clock  Mon - Sun 8.00 AM - 8.00 PM
fb
instagram
play store
pinterest

How to add middleware in Vue JS 3

writter  Hariom Prajapati
Date  22 Jan 2023
Language  Vue JS
How to add middleware in Vue JS 3

How to add middleware in Vue JS 3

In this tutorial we learn about route middleware in vue js 3.

What is middleware?

 

In simple language, middleware can be used to validate HTTP and HTTPS requests of the browser.

 

Usually if we need to authenticate a page in a small project in Vue JS, we do the validation by checking the component script inside that page and if that user is not authenticated, we redirect him to the page Redirect to login or sign up for. We redirect. In this article, we will create an authentication middleware with the help of Vue Router, which we can implement in small and large projects. Setting up the middleware this way speeds up our application and doesn't require us to write a lot of code to authenticate the user.

 

So, let's implement our middleware concept in vue js.

 

Step 1 - Install Vue project 

If you don't have any Vue projects click here to install the Vue project.

 

Step 2 - Install vue router dependencies

If vue router is not installed in your project then run this command

 

npm install vue-router

 

Click here to see full information about vue router

 

Step 3 - Go to src/router/index.js

Add this code into index.js file

// add route name here to make private page
const privateRoutes = [
  'dashboard',
  'my-profile',
];


router.beforeEach((to, from, next) => {
  if (privateRoutes.includes(to.name)) {
    // redirect to login page with next url
    if (!localStorage.getItem('accessToken')) {
      next(`${'/login?next='}${to.fullPath}`);
    }  
  }

  // redirect to dashboard page if user is already logged in
  if (to.name === 'login') {
    if (localStorage.getItem('accessToken')) {
      next('/dashboard');
    }
  }
 
  next();
});

 

In the above code we have created a private route variable and added the private page names into the privateRoute variable.

 

To check the login status we need to add the access to the localStorage function while requesting the login API function.

 

Here is the full code of index.js file with middleware.

 

Note : In this page we are using the example routes. You can customize the routers according to the requirement.

 

src/router/index.js

import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
    },
    {
      path: "/login",
      name: "login",
       component: () => import("../views/LoginView.vue"),
    },
    {
      path: "/sign-up",
      name: "sign-up",
       component: () => import("../views/SignUpView.vue"),
    },
    {
      path: "/dashboard",
      name: "dashboard",
       component: () => import("../views/DashboardView.vue"),
    },
    {
      path: "/my-profile",
      name: "my-profile",
       component: () => import("../views/MyProfileView.vue"),
    },
    {
      path: "/about",
      name: "about",
      component: () => import("../views/AboutView.vue"),
    },
  ],
});


// add route name here to make private page
const privateRoutes = [
  'dashboard',
  'my-profile',
];


router.beforeEach((to, from, next) => {
  if (privateRoutes.includes(to.name)) {
    // redirect to login page with next url
    if (!localStorage.getItem('accessToken')) {
      next(`${'/login?next='}${to.fullPath}`);
    }  
  }

  // redirect to dashboard page if user is already logged in
  if (to.name === 'login') {
    if (localStorage.getItem('accessToken')) {
      next('/dashboard');
    }
  }
 
  next();
});

export default router;

 

Step 4 - Run the development server.

Now start the npm server to check the middleware.

 

Click here to download the source code.