Skip to content

nexa-router

Client-side router with path matching, navigation guards, and reactive signals.

createRouter

Creates a router instance with routes, optional mode, and guards.

ts
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): Router

Returns a Router object with the following properties:

ts
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:

ts
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')

A method on the router instance. Runs all registered guards before changing the route. If any guard returns false, navigation is blocked.

ts
await router.navigate('/dashboard')

beforeEach

Registers a navigation guard that runs before every route change:

ts
router.beforeEach((to, from) => {
  if (to.startsWith('/admin') && !isLoggedIn) return false
  return true
})

Guards can also be async:

ts
router.beforeEach(async (to, from) => {
  const allowed = await checkPermission(to)
  return allowed
})

RouterView

A component that automatically renders the active route's component:

html
<template>
  <RouterView :router="router" />
</template>

A component that renders an anchor tag with client-side navigation:

ts
import { Link } from 'nexa-router'
html
<template>
  <Link to="/about" :router="router">About</Link>
</template>

createGuards

Creates a standalone guard registry (useful for testing or manual guard execution):

ts
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.

ts
import { matchPath } from 'nexa-router'

function matchPath(
  pattern: string,
  path: string
): Record<string, string> | null

Returns a params object on match, or null if no match.

Examples:

ts
matchPath('/users/:id', '/users/42')
// Returns: { id: '42' }

matchPath('/users/:id', '/posts/1')
// Returns: null

Released under the MIT License.