Skip to content
Updated April 2026Edit this page ↗

Router

@termuijs/router gives your terminal app screen-based navigation with a history stack, dynamic parameters, and event hooks.

Installation

TYPESCRIPT
npm install @termuijs/router

Setting up routes

Register routes with addRoute(). Each route maps a path pattern to a component loader:

TYPESCRIPT
import { Router } from '@termuijs/router'
 
const router = new Router({ initialPath: '/' })
 
router.addRoute('/',          () => HomeScreen)
router.addRoute('/settings',  () => SettingsScreen)
router.addRoute('/users/[id]', () => UserScreen)
 
// Or register several at once
router.addRoutes([
    { path: '/logs',        component: () => LogScreen },
    { path: '/logs/[...slug]', component: () => LogDetail },
])
TYPESCRIPT
// Push a new route onto the history stack
router.push('/settings')
console.log(router.currentPath)  // → '/settings'
 
// Push a dynamic route
router.push('/users/42')
console.log(router.current)
// → { route: ..., params: { id: '42' } }
 
// Go back
router.back()
console.log(router.currentPath)  // → '/settings'
 
// Replace. swaps the current entry without growing history
router.replace('/help')
console.log(router.historyLength)  // same as before

Dynamic parameters

Use bracket syntax for dynamic segments. This is the same convention as Next.js file-based routing:

PatternMatchesParams
/users/[id]/users/42{ id: '42' }
/[...slug]/a/b/c{ slug: 'a/b/c' }
/settings/settings{}

Listening for route changes

The router has an events emitter you can subscribe to:

TYPESCRIPT
router.events.on('navigate', (match) => {
    console.log('Navigated to', match.route.path)
    console.log('Params:', match.params)
})
 
router.events.on('back', (match) => {
    console.log('Went back to', match?.route.path)
})

API reference

Method / PropertyDescription
addRoute(path, component, layout?)Register a single route
addRoutes(routes)Register multiple routes at once
push(path)Navigate to a new path
replace(path)Replace the current history entry
back()Go to the previous path
currentPathThe current path string
currentThe current RouteMatch (route + params), or null
historyLengthNumber of entries in the history stack
canGoBackWhether there's a previous entry to go back to