Navigation Guards
Introduction
Navigation guards in @esmx/router provide hooks into the route transition process, allowing you to control navigation, perform checks, redirect users, or execute side effects at different stages of a route change.
Type Definitions
RouteConfirmHook
- Type Definition:
A confirmation guard that can approve, reject, or redirect navigation. Used by beforeEach() and beforeEnter.
RouteConfirmHookResult
- Type Definition:
Return values for confirmation guards:
voidorundefined: Allow navigation to proceedfalse: Cancel the navigationRouteLocationInput: Redirect to a different locationRouteHandleHook: Provide a custom handle function for the route
RouteNotifyHook
- Type Definition:
A notification hook called after navigation completes. Cannot cancel or redirect navigation. Used by afterEach().
RouteVerifyHook
- Type Definition:
A verification hook that returns a boolean. Used in layer keep-alive logic.
RouteHandleHook
- Type Definition:
A handle hook for custom route handling logic. Can only be called once per navigation.
RouteHandleResult
- Type Definition:
Return type of handle hooks. The result is accessible via route.handleResult.
Global Guards
router.beforeEach()
- Parameters:
guard: RouteConfirmHook— Guard function
- Returns:
() => void— Unregister function
Registers a global guard called before every navigation. Guards are called in registration order. If any guard cancels or redirects, subsequent guards are skipped.
router.afterEach()
- Parameters:
guard: RouteNotifyHook— Hook function
- Returns:
() => void— Unregister function
Registers a global hook called after every navigation completes. After-each hooks cannot affect navigation — they are purely for side effects like analytics, title updates, or logging.
Per-Route Guards
beforeEnter
- Type:
RouteConfirmHook
Guard called before entering a specific route. Defined in the route configuration.
beforeUpdate
- Type:
RouteConfirmHook
Guard called when the route is reused but parameters change (e.g., navigating from /user/1 to /user/2).
beforeLeave
- Type:
RouteConfirmHook
Guard called before leaving a specific route. Useful for preventing navigation when there are unsaved changes.
Guard Execution Order
When a navigation occurs, guards are executed in the following order:
- beforeLeave guards on the route being left
- Global beforeEach guards (in registration order)
- beforeUpdate guards on reused routes
- beforeEnter guards on the target route configuration
- Navigation is executed
- Global afterEach hooks (in registration order)
Guard Cleanup
All guard registration methods return an unregister function. Call it to remove the guard:
This is especially important in component-based frameworks where guards registered in component lifecycle hooks should be cleaned up when the component unmounts.