Skip to content

URL Utilities

1 min read

_/core contains helpers for building paths and URLs for both backend and frontend routes:

ts
import { apiRouteMap, pageRouteMap } from "_/core";

Both maps are keyed by route name, so an editor completes the routes you actually have.

API Routes ​

pages/example/page.tsx
ts
import { apiRouteMap } from "_/core";

const users = apiRouteMap["users/[id]"];

users.path([123]);
// -> "/api/users/123"

users.path([123], { query: { include: "posts" } });
// -> "/api/users/123?include=posts"

users.href("https://api.example.com", [123]);
// -> "https://api.example.com/api/users/123"

users.href("https://api.example.com", [123], { query: { include: "posts" } });
// -> "https://api.example.com/api/users/123?include=posts"

Multiple parameters follow path order:

ts
// route: posts/[userId]/comments/[commentId]
const comments = apiRouteMap["posts/[userId]/comments/[commentId]"];

comments.path([456, 789]);
// -> "/api/posts/456/comments/789"

When every parameter is optional, the tuple can be left out:

ts
// route: users/{id}
apiRouteMap["users/{id}"].path();
// -> "/api/users"

Page Routes ​

pageRouteMap works the same way, with the frontend's base path:

ts
import { pageRouteMap } from "_/core";

const docs = pageRouteMap["docs/{...path}"];

docs.path([["guide", "getting-started"]]);
// -> "/docs/guide/getting-started"

docs.href("https://example.com", [["guide", "getting-started"]]);
// -> "https://example.com/docs/guide/getting-started"

Query strings use the same second argument:

ts
pageRouteMap["blog/{category}"].path([{ category: "news" }], {
  query: { page: 2 },
});
// -> "/blog/news?page=2"

These builders only produce strings. They do not load the fetch client, its schemas, or perform a request.

Released under the MIT License.