nexa-router
Client-side router with path matching, navigation guards, and reactive signals.
createRouter
Creates a router instance with routes, optional mode, and guards.
import { createRouter } from 'nexa-router'
interface RouteDef {
path: string
component: Component
}
type Guard = (to: string, from: string) => boolean | Promise<boolean>
interface RouterConfig {
routes: RouteDef[]
mode?: 'hash' | 'history'
guards?: { beforeEach: Guard[] }
}
function createRouter(config: RouterConfig): RouterReturns a Router object with the following properties:
interface Router {
navigate(path: string): Promise<void>
beforeEach(guard: Guard): void
currentRoute: Signal<RouteDef | null>
currentPath: Signal<string>
params: Signal<Record<string, string>>
query: Signal<Record<string, string>>
}Example:
const router = createRouter({
routes: [
{ path: '/', component: Home },
{ path: '/user/:id', component: UserProfile },
{ path: '*', component: NotFound },
],
mode: 'history',
})
// Navigate (runs guards first)
await router.navigate('/user/42')navigate
A method on the router instance. Runs all registered guards before changing the route. If any guard returns false, navigation is blocked.
await router.navigate('/dashboard')beforeEach
Registers a navigation guard that runs before every route change:
router.beforeEach((to, from) => {
if (to.startsWith('/admin') && !isLoggedIn) return false
return true
})Guards can also be async:
router.beforeEach(async (to, from) => {
const allowed = await checkPermission(to)
return allowed
})RouterView
A component that automatically renders the active route's component:
<template>
<RouterView :router="router" />
</template>Link
A component that renders an anchor tag with client-side navigation:
import { Link } from 'nexa-router'<template>
<Link to="/about" :router="router">About</Link>
</template>createGuards
Creates a standalone guard registry (useful for testing or manual guard execution):
import { createGuards } from 'nexa-router'
const guards = createGuards()
guards.beforeEach((to, from) => {
return isAuthenticated || to === '/login'
})
await guards.runGuards('/admin', '/')matchPath
Matches a path string against a route pattern with :param support.
import { matchPath } from 'nexa-router'
function matchPath(
pattern: string,
path: string
): Record<string, string> | nullReturns a params object on match, or null if no match.
Examples:
matchPath('/users/:id', '/users/42')
// Returns: { id: '42' }
matchPath('/users/:id', '/posts/1')
// Returns: null