🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Reading Search Params

A search param is the part of the address after the question mark. The page reads it and filters the list.

The page reads the query

The page awaits searchParams, then filters the books. No query means no filter.

export default async function Home({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const { q } = await searchParams;
  const books = searchBooks(q ?? "");

The filter checks title and author

The filter matches the title or the author. The match ignores case.

export function searchBooks(q: string): Book[] {
  const query = q.trim().toLowerCase();
  if (!query) return getBooks();
  return getBooks().filter(
    (book) =>
      book.title.toLowerCase().includes(query) ||
      book.author.toLowerCase().includes(query),
  );
}

Example

curl -s "http://localhost:3111/?q=dune" | grep -o 'Dune\|The Hobbit' | sort -u

Key points

  • Search param: a named value in the address, after the question mark
  • In ?q=dune, the name is q and the value is dune.
  • searchParams is a Promise in this version. The page must await it.
  • An empty search shows all five books. A search for dune shows one.
  • A search with no match shows zero books. The list is empty, not an error.
  • ?? is the fallback. q ?? "" means the search word, or an empty string when there is none.

In this example, the check asks for the home page with ?q=dune. The page reads the query, filters the five books, and shows one. The answer holds Dune and no Hobbit, so the filter worked. The same address with no query shows all five books, and ?q=zzz shows none. The address carries the search, and the page reads it.

Note

The search box writes the address, and the page reads it back. The two halves meet in the address.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What does ?q=dune show?