Adding Vue Navigation Guard

Learn how to implement a navigation guard in a Vue.js application.

Introduction to navigation guard implementation

Now that we have all the components for the authentication part, we can add a navigation guard and protect the home page. Take a look at how our ./router/index.js looks without a navigation guard.

Press + to interact
import Vue from "vue";
import VueRouter from "vue-router";
import auth from "./routes/auth"
import home from "./routes/home"
import error404 from "./routes/error404"
Vue.use(VueRouter);
const routes = [
{ path: '/', redirect: '/login' },
...auth,
...home,
...error404,
{
path: '*',
redirect: 'error-404',
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
scrollBehavior() {
return { x: 0, y: 0 }
},
});

Implementing the navigation guard

...