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:


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): void

Example

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): void

Example

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

  1. Global Guards: Executed in the order they were registered.
  2. Route-Specific Guards: Executed in the order they were registered.
  3. The first guard that returns false or a redirect string stops execution immediately; subsequent guards are skipped.
edit this doc