Blog

How to use and update search parameters in Next.JS 14+

2 May 2024
By Denis

How to use and update search parameters in Next.JS 14+

In this article, we will learn how to use search parameters in NextJS. We will use the useSearchParams hook from next/navigation to read and update the search parameters.

What are search parameters?

Search parameters are the part of the URL that comes after the ? character. For example, in the URL https://example.com?name=John, the search parameter is name=John.

They are helpful when you want to pass data from one page to another. For example, if you have a page with search, you can pass the search query as a search parameter: https://example.com/search?query=hello.

How to use search parameters in NextJS

The best way to use search parameters in NextJS is to use the useSearchParams hook from next/navigation. This hook gives you access to the search parameters and allows you to read and update them.

This is a client component hook. So make sure to use it in a client component only.

Here is an example of how we use the useSearchParams hook in SupaLaunch starter kit for handling authentication errors from Next.JS server actions:

'use client'

import {useSearchParams} from "next/navigation";
import {XCircleIcon} from "lucide-react";


export default function AuthForm({isSignUpInit}: {
    isSignUpInit: boolean
}) {
    .......

    const searchParams = useSearchParams()
    const error = searchParams.get('error')

    return (
        <>

            .........
            {
                error &&
                <div role="alert" className="alert alert-error mx-auto w-full mt-5">
                    <XCircleIcon/> <span>{error}</span>
                </div>
            }
            .........
        </>
    )
}

In the above example, we are using the useSearchParams hook to get the search parameters from the URL. We then check if there is an error in the search parameters and display it as an alert.

How to programmatically update search parameters

You can also update the search parameters programmatically using the useSearchParams hook. Here is an example of how you can update the search parameters in NextJS:

import {useSearchParams, useRouter, usePathname} from "next/navigation";

function updateSearchParam({key, value}: {
    key: string,
    value: string
}): string {
const pathname = usePathname();
    const searchParams = useSearchParams()
    const params = new URLSearchParams(searchParams);
    if (value) {
        // set the search parameter if value is not empty
        params.set(key, value)
    } else {
        params.delete(key)
    }
    return `${pathname}?${params.toString()}`
}

function updateSearchParamForCurrentPage({key, value}: {
    key: string,
    value: string
}) {
    const {replace} = useRouter();

    const newUrl = updateSearchParam({key, value})
    replace(newUrl)
}

In the above example, we are using the useSearchParams hook to get the search parameters from the URL. We then update the search parameters based on the key and value passed to the updateSearchParam function.

How to update search params for the current page

This is simple. First, get the new URL using the updateSearchParam function and then use the replace function to navigate to the new URL.

This is shown in the updateSearchParamForCurrentPage function in the above example.

Conclusion

In this article, we learned how to use search parameters in NextJS. We used the useSearchParams hook from next/navigation to read and update the search parameters. This hook is very useful when you want to pass data from one page to another in NextJS.

Launch your SaaS with our Supabase + NextJS Course

Learn how to create an AI-powered SaaS from scratch using Supabase and Next.js. We will guide you from zero to launch. What you will learn:

  • Stripe payments
  • Authentication with email/password and social logins
  • AI functionality: Chat, Langchain integration, OpenAI API streaming and more
  • How to setup emails, file storage, etc.