A lightweight, type-safe route builder utility for Next.js
Build dynamic and optional routes with ease and full TypeScript support.
In Next.js projects, especially with dynamic routes, managing route strings manually can lead to typos, inconsistencies, and bugs.
This package lets you define your route patterns once and then build URLs with typed parameters, ensuring correctness across your app.
- Define routes with dynamic (
:param
) and optional (:param?
) segments - Type-safe parameter enforcement in TypeScript
- Automatic URL encoding of parameter values
- Removes optional params when not provided
- Lightweight and zero dependencies
npm install nextjs-route-utils
# or
yarn add nextjs-route-utils
More examples in the test file
const user = createRoute<{ userId: string }>("/users/:userId");
user({ userId: "abc" }); // /users/abc
const post = createRoute<{ userId: string; postId: number }>(
"/users/:userId/posts/:postId"
);
post({ userId: "john", postId: 42 }); // /users/john/posts/42