Navigation guards
Guards run before or after navigation, so you can block, redirect or log route changes.
In this page:
Syntax
router.beforeEach((to, from) => {
if (condition) {
return '/redirect-path';
}
// returning nothing allows navigation
});
Navigation guards
router.beforeEach((to, from) => ...) runs before each navigation and can return false to cancel, a route location to redirect, or nothing to continue.
Per-route beforeEnter and in-component guards also exist. Use meta fields, such as requiresAuth, to drive guards.
Note:
Return a route location from a guard to redirect the user.
Example: Navigation guards
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const loggedIn = false;
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [
{ path: "/", component: { template: "<p>Public home</p>" } },
{ path: "/login", component: { template: "<p>Please log in</p>" } },
{ path: "/admin", meta: { requiresAuth: true }, component: { template: "<p>Secret admin</p>" } },
],
});
router.beforeEach((to) => {
if (to.meta.requiresAuth && !loggedIn) return "/login";
});
Vue.createApp({}).use(router).mount("#app");
router.push("/admin").then(async () => {
await Vue.nextTick();
console.log("landed on:", router.currentRoute.value.path, "-", document.querySelector("p").textContent);
});
</script>
</body>
</html>
<!-- Output:
Rendered: Please log in
console: landed on: /login - Please log in
-->
Live Example
Related Topics
Common Mistakes
- Creating redirect loops
- Using the old next() callback incorrectly
- Protecting only on the client
Chapter Summary
- beforeEach runs before navigation
- Return false or a location to block or redirect
- meta fields drive rules
- Also secure the server
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: