Skip to content

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

Terminal window
npm install @mongez/concat-route

Quick 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 falsy
concatRoute("/foo//", "//bar///", "baz"); // "/foo/bar/baz"

Glue path segments — leading slash guaranteed, falsy values silently dropped, embedded slashes collapsed.

Mental model

InputWhat you get
concatRoute(a, b, c)Glue a, b, c into a path. Slashes are normalised — result always starts with /, no junk.
Falsy segmentsDropped silently. Use this to thread optional pieces without conditionals.
Empty inputReturns "/". The function never returns an empty string.

Scope boundaries

ConcernLives inWhy
Query string ?a=1&b=2@mongez/query-stringConcat-route treats "?q=1" as a segment and wraps it in /. Use a real parser.
Absolute URLs with protocol://hostBuilt-in URLThe slash-collapse pass destroys https://.
Route pattern matching (/users/:id)@mongez/react-routerDifferent problem entirely.
EncodingencodeURIComponentConcat-route does not encode.

Why a function instead of path.posix.join?

  1. Always leading /. URL paths need it; path.posix.join doesn’t add it.
  2. Drops falsy segments silently. Lets you spread optional pieces without conditionals.
  3. Browser-safe. node:path isn’t available in the browser without polyfilling.
  4. Collapses arbitrary slash runs, including embedded // inside a single segment.

Where to go next