Jacob Paris
← Back to all content

Remove empty query parameters from URLs

While working with HTML forms, you'll often end up with query parameters in the URL that don't have a value. For example, if you have a form with a search input and the user submits the form without entering anything, you'll end up with a URL like ?search=

If your app doesn't have a use-case for empty query parameters, you can remove them from the URL by calling a function that throws a redirect response.

ts
async function clearEmptyParams(url: URL) {
let shouldRedirect = false
for (const [key, value] of url.searchParams.entries()) {
if (value === "") {
url.searchParams.delete(key)
shouldRedirect = true
}
}
if (shouldRedirect) {
throw redirect(url.toString())
}
}

You can then call this function in your loader function on any route that uses GET forms.

ts
export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url)
await clearEmptyParams(url)
}
Professional headshot
Moulton
Moulton

Hey there! I'm a developer, designer, and digital nomad building cool things with Remix, and I'm also writing Moulton, the Remix Community Newsletter

About once per month, I send an email with:

  • New guides and tutorials
  • Upcoming talks, meetups, and events
  • Cool new libraries and packages
  • What's new in the latest versions of Remix

Stay up to date with everything in the Remix community by entering your email below.

Unsubscribe at any time.