tezvyn:

Navigation Guards: Vue's Route Bouncers

AI-drafted, machine-checkedSource: router.vuejs.orgintermediate

Think of navigation guards as bouncers for your app's routes. They intercept route changes to check permissions or fetch data before rendering a page. The old `next()` callback is a trap; accidentally calling it twice can break navigation.

WHY IT EXISTS: Web apps often need to control access to certain pages or perform actions before a user navigates. Without a formal mechanism, this logic gets scattered and becomes hard to manage. Navigation guards provide a centralized, predictable system for intercepting route changes.

THE MENTAL MODEL: A navigation guard is a bouncer at the door of a route. Before letting a user "enter" a new page, the bouncer checks their credentials. Based on the rules, it can either let them in, redirect them to a different door (like a login page), or deny entry altogether, resetting the URL if needed.

HOW IT WORKS: You register a function with the router, most commonly using router.beforeEach for global checks. This function receives the target route (to) and the current route (from). Your function's return value controls the navigation. Return true or undefined to proceed, false to cancel, or a route object like { name: 'Login' } to redirect. The router waits for your guard, even if it's an async function, before continuing.

WHEN TO USE IT: Use guards for tasks that must happen before a route is rendered. Three common cases are: first, checking for a valid authentication token and redirecting to login if it's missing; second, verifying user permissions for a specific admin section; third, fetching critical data that a component needs before it can be displayed.

WHEN NOT TO USE IT: Avoid using global guards for logic that is highly specific to a single component's internal state. The primary footgun is the legacy next() callback. If you see it, know that it must be called exactly once per code path. Modern practice avoids next() entirely by returning values, which is safer and clearer.

ONE CANONICAL EXAMPLE: The most common use case is protecting routes. A global beforeEach guard checks if the target route requires authentication and if the user is logged in. If the route is protected and the user is not authenticated, the guard cancels the current navigation and returns a new route object, redirecting the user to the login page. This prevents an infinite redirect loop by also checking that the target route isn't the login page itself.

Read the original → router.vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.