Skip to content

router

Minimal client-side router with hooks, params, redirects, and 404.

/**
* Minimal client-side router.
*
* @param routes An object mapping paths to handlers, handler objects, or redirect strings.
* - handler: (params?: Record<string, string>, query?: Record<string, string>) => void
* - before: Optional per-route before hook.
* - after: Optional per-route after hook.
* - string: Redirect path.
* @param options Optional:
* - before: Global before hook.
* - after: Global after hook.
* - 404: Not found handler.
* - redirects: Array of { from: string[], to: string }
* - hash: Optional hash mode (default false).
* @returns RouteInfo
*/
router(
routes: {
[path: string]:
| ((params?: Record<string, string>, query?: Record<string, string>) => void)
| {
handler: (params?: Record<string, string>, query?: Record<string, string>) => void,
before?: () => void,
after?: () => void
}
| string // redirect
},
options?: {
before?: () => void,
after?: () => void,
404?: () => void,
redirects?: Array<{ from: string[], to: string }>
}
): RouteInfo

Set up client-side routing with route handlers, hooks, redirects, and 404 handling. Use with route for reactive route info and navigate for programmatic navigation.

import { effect } from "@hellajs/core";
import { router, route } from "@hellajs/router";
// Define routes and handlers
router({
"/": () => { /* home handler */ },
"/about": {
handler: () => { /* about handler */ },
before: () => { /* before hook */ },
after: () => { /* after hook */ }
},
"/user/:id": (params) => {
console.log(params.id); // dynamic param
},
"/old": "/new", // redirect
}, {
before: () => { /* global before */ },
after: () => { /* global after */ },
404: () => { /* not found */ },
redirects: [
{ from: ["/legacy"], to: "/" }
]
});
// Access current route reactively
effect(() => {
const r = route();
console.log(r.path, r.params, r.query);
});