TypeScript

URL Builder with Type-Safe Query

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build URLs with a clean query-param API. Skips null/undefined automatically, encodes everything, and accepts arrays for repeated keys. Avoids manual string concatenation.
TypeScript
Raw
type QueryValue = string | number | boolean | null | undefined | (string | number | boolean)[];

export function buildUrl(base: string, params: Record<string, QueryValue> = {}): string {
  const url = new URL(base, typeof window === 'undefined' ? 'http://placeholder' : window.location.href);
  for (const [k, v] of Object.entries(params)) {
    if (v === null || v === undefined) continue;
    if (Array.isArray(v)) v.forEach(item => url.searchParams.append(k, String(item)));
    else                  url.searchParams.set(k, String(v));
  }
  // If `base` was already absolute, return the full URL; otherwise return path+search.
  return /^https?:\/\//i.test(base) ? url.toString() : url.pathname + url.search;
}

buildUrl('/api/users', { active: true, role: ['admin', 'editor'], page: 1, q: null });
// '/api/users?active=true&role=admin&role=editor&page=1'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.