What is the TypeScript Type of Next.js searchParams?

Hemanta Sundaray

Published September 17, 2023


In Next.js (app directory), useSearchParams is a client-side hook that allows you to read the current URL’s query string.

Note

The query string is an optional collection of name/value pairs. They appear at the end of the path in URLs. The query string starts with a question mark (?) and name/value pairs are separated by ampersands (&).

For example, in the URL www.hemantasundaray.com/blog?category=typescript&year=2023, the query string is ?category=typescript&year=2023.

The path is part of the URL after the hostname. So, in a request to www.hemantasundaray.com/blog, the path is /blog.

You use it as follows:

const serachParams = useSerachParams();

useSearchParams returns a read-only version of the URLSearchParams interface, which defines utility methods to work with the query string.

If you are using TypeScript in your Next.js project, you might come across cases where you need to type annotate searchParams. How do you do it?

Simply import ReadonlyURLSearchParams from next/navigation and then specify the type of searchParams as ReadonlyURLSearchParams.

Here's a minimal example:

import { ReadonlyURLSearchParams } from "next/navigation";
 
interface MyInterface {
  searchParams: ReadonlyURLSearchParams;
}