Concat Route
A single-function utility for joining path segments into one normalised leading-slash path. The helper you reach for when you have a base path from configuration, a feature prefix from a constant, and an ID from a URL parameter — and you don’t want to write if (base.endsWith("/")) … six times.
The function is path-only: it understands / separators between segments, and that’s it. Not a URL builder, not a query-string parser, not a router pattern matcher.
Highlighted features
Leading slash guaranteed
concatRoute(“api”, “users”) returns “/api/users” — never the bare “api/users” you’d get from path.posix.join.
Falsy segments dropped
concatRoute(“/base”, locale ?? "", “/products”) just works — no conditionals when threading optional pieces.
Slash runs collapse
concatRoute(“/foo//”, “//bar///”, “baz”) → “/foo/bar/baz”. Junk in, clean path out.
~10 lines, zero deps
Browser-safe (no node:path polyfill), no runtime dependencies. Default-exports the entire public surface.
Install
npm install @mongez/concat-routeyarn add @mongez/concat-routepnpm add @mongez/concat-routeQuick peek
import concatRoute from "@mongez/concat-route";
concatRoute("api", "/users", String(userId)); // "/api/users/42"concatRoute("/", "/dashboard", ""); // "/dashboard"concatRoute("/base", locale ?? "", "/products"); // "/base/products" if locale is falsyconcatRoute("/foo//", "//bar///", "baz"); // "/foo/bar/baz"Glue path segments — leading slash guaranteed, falsy values silently dropped, embedded slashes collapsed.
Mental model
| Input | What you get |
|---|---|
concatRoute(a, b, c) | Glue a, b, c into a path. Slashes are normalised — result always starts with /, no junk. |
| Falsy segments | Dropped silently. Use this to thread optional pieces without conditionals. |
| Empty input | Returns "/". The function never returns an empty string. |
Scope boundaries
| Concern | Lives in | Why |
|---|---|---|
Query string ?a=1&b=2 | @mongez/query-string | Concat-route treats "?q=1" as a segment and wraps it in /. Use a real parser. |
Absolute URLs with protocol://host | Built-in URL | The slash-collapse pass destroys https://. |
Route pattern matching (/users/:id) | @mongez/react-router | Different problem entirely. |
| Encoding | encodeURIComponent | Concat-route does not encode. |
Why a function instead of path.posix.join?
- Always leading
/. URL paths need it;path.posix.joindoesn’t add it. - Drops falsy segments silently. Lets you spread optional pieces without conditionals.
- Browser-safe.
node:pathisn’t available in the browser without polyfilling. - Collapses arbitrary slash runs, including embedded
//inside a single segment.
Where to go next
- Concat route — full signature, edge cases
- Recipes — common patterns