Skip to content

Instantly share code, notes, and snippets.

@martinhj
Created November 21, 2023 10:03
Show Gist options
  • Save martinhj/30ce35b4bc762fe36a5d612d66b19807 to your computer and use it in GitHub Desktop.
Save martinhj/30ce35b4bc762fe36a5d612d66b19807 to your computer and use it in GitHub Desktop.
Convert NodeJS' ParseUrlQuery to browser API URLSearchParams
import type { ParsedUrl } from 'next/dist/shared/lib/router/utils/parse-url'
export function convertUrlQueryToUrlSearchParams(
queryArgs: ParsedUrl['query'],
) {
const searchparams = new URLSearchParams()
Object.entries(queryArgs)
.filter(([key, value]) => Boolean(value))
.forEach(
([key, value]) =>
value !== undefined &&
(Array.isArray(value)
? value.forEach(_value => searchparams.append(key, _value))
: searchparams.append(key, value)),
)
return searchparams
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment