typed-next-router
v0.0.5
Published
Typed helpers for Next.js routing.
Readme
typed-next-router
Typed helpers for Next.js routing.
What It Solves
- Prevents route path typos at compile time
- Validates dynamic path params and query keys/values from route metadata
Type-Safe Next.js Surfaces
| Next.js surface | Type safety added | Example |
| --- | --- | --- |
| next/link (Link) | Restricts href to registered routes and enforces route-specific pathParams/queryParams shape | <Link href={{ path: '/dashboard' }} /> |
| next/navigation (useRouter) | Type-checks push/replace/prefetch inputs with the same route contract (path, dynamic params, query keys/values) | router.push({ path: '/users/[id]', pathParams: { id: '42' } }) |
| next/navigation (useSearchParams) | Narrows search param key/value types per route via useTypedSearchParams(path) on get/set/append/delete/has | searchParams.set('mode', 'edit') |
Install
npm install typed-next-routerBasic Usage
import { Link, useTypedRouter } from 'typed-next-router';
function Example() {
const router = useTypedRouter();
router.push({
path: '/users/[id]',
pathParams: { id: '42' },
});
return (
<Link href={{ path: '/dashboard' }}>
Go dashboard
</Link>
);Route Metadata
// route-map.ts
import type { RouteMapShape } from 'typed-next-router';
export const paramsMap = {
'/dashboard': {
queryParams: {
tab: ['overview', 'alerts'],
search: [],
},
},
'/users/[id]': {
pathParams: ['id'],
queryParams: {
mode: ['view', 'edit'],
},
},
} as const satisfies RouteMapShape;[] means dynamic string value for that query key.
search: []=>searchaccepts any stringmode: ['view', 'edit']=> only'view' | 'edit'
Module Augmentation
// typed-next-router.generated.d.ts
import 'typed-next-router';
declare module 'typed-next-router' {
export interface RouteRegistry {
path: '/dashboard' | '/users/[id]';
map: typeof import('./route-map').paramsMap;
}
}FYI: generating route metadata is easier with path-typegen. and you can change
satisfies RouteMapShapetosatisfies Partial<RouteMapShape<PathType>>
