Route Guards
Route Guards allow you to protect routes with authentication checks, authorization, or other custom logic.
Guards can block navigation entirely or redirect the user to a different location.
Guard Return Values
A guard function can return:
true: Allow the navigation.false: Block the navigation (remains on the current page).string: Redirects the user to the specified path string.Promise<boolean | string>: Async checks (e.g. database fetches) are fully supported.
Global Guards
Global guards execute on every navigation event, before any route-specific guards.
typescript
1function registerGlobalGuard(2 guard: (3 pathname: string,4 query: Record<string, unknown>,5 data: Record<string, unknown>6 ) => boolean | string | Promise<boolean | string>7): voidExample
javascript
1import { registerGlobalGuard } from '@beforesemicolon/router'2 3// Authentication guard4registerGlobalGuard((pathname, query, state) => {5 const publicPages = ['/login', '/register', '/404']6 7 if (!publicPages.includes(pathname) && !userIsLoggedIn()) {8 return '/login' // Redirect to login9 }10 11 return true // Allow navigation12})Route-Specific Guards
Route-specific guards run only when navigating to a path that matches the registered pattern.
typescript
1function registerRouteGuard(2 pattern: string,3 guard: (4 pathname: string,5 query: Record<string, unknown>,6 data: Record<string, unknown>7 ) => boolean | string | Promise<boolean | string>8): voidExample
javascript
1import { registerRouteGuard } from '@beforesemicolon/router'2 3// Role-based authorization guard (Async)4registerRouteGuard('/admin/:section', async (pathname, query, state) => {5 try {6 const hasAccess = await checkAdminPermissions()7 return hasAccess ? true : '/unauthorized'8 } catch {9 return false // Block navigation on error10 }11})Guard Execution Order
- Global Guards: Executed in the order they were registered.
- Route-Specific Guards: Executed in the order they were registered.
- The first guard that returns
falseor a redirectstringstops execution immediately; subsequent guards are skipped.