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
function registerGlobalGuard(
guard: (
pathname: string,
query: Record<string, unknown>,
data: Record<string, unknown>
) => boolean | string | Promise<boolean | string>
): voidExample
javascript
import { registerGlobalGuard } from '@beforesemicolon/router'
// Authentication guard
registerGlobalGuard((pathname, query, state) => {
const publicPages = ['/login', '/register', '/404']
if (!publicPages.includes(pathname) && !userIsLoggedIn()) {
return '/login' // Redirect to login
}
return true // Allow navigation
})Route-Specific Guards
Route-specific guards run only when navigating to a path that matches the registered pattern.
typescript
function registerRouteGuard(
pattern: string,
guard: (
pathname: string,
query: Record<string, unknown>,
data: Record<string, unknown>
) => boolean | string | Promise<boolean | string>
): voidExample
javascript
import { registerRouteGuard } from '@beforesemicolon/router'
// Role-based authorization guard (Async)
registerRouteGuard('/admin/:section', async (pathname, query, state) => {
try {
const hasAccess = await checkAdminPermissions()
return hasAccess ? true : '/unauthorized'
} catch {
return false // Block navigation on error
}
})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.