snippet · 2026-06-20 · 3 min

A URL query-state helper

A small immutable helper for updating typed search parameters.

  • typescript
  • urls
  • utilities

The helper

export function withQuery(current: URLSearchParams, updates: Record<string, string | undefined>) {
  const next = new URLSearchParams(current);
  for (const [key, value] of Object.entries(updates)) {
    if (value === undefined || value === "") next.delete(key);
    else next.set(key, value);
  }
  return next.toString();
}

This helper deliberately does not validate supported keys or values. Parse and validate at the route boundary, then pass only known updates. Use router.replace for transient typing and router.push when the change should create a history step.