How to Manage URL Query Parameters in Next.js 14

Saleem Raza
2 min readNov 28, 2024

--

In this article, I’ll guide you through handling specific query parameters in Next.js 14. We’ll cover how to:

  1. Retrieve specific query parameters from the URL.
  2. Remove a specific query parameter from the URL without reloading the page.

By the end, you’ll understand how to leverage Next.js 14 features like usePathname, useSearchParams, and useRouter to create dynamic, interactive user experiences.

Scenario: Showing and Removing Query Parameters

Let’s say you want to display a popup when the current URL contains the query parameter email=true. Once the user closes the popup, the email=true parameter should be removed from the URL, all without refreshing the page.

Here’s how to do it step-by-step.

Import the Necessary Hooks

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

Initialize Variables

Next, set up the variables to manage the URL path, query parameters, and router functionality:

const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

Retrieve the value of the email query parameter:

const emailQuery = searchParams.get(“email”);

Add Logic to Handle the Query Parameter

Now, implement the logic to open the popup and update the URL:

if (emailQuery) {

// Open the popup
setEmailModalOpen(true);
// Create a copy of the current query parameters
const nextSearchParams = new URLSearchParams(searchParams.toString());
// Remove the ‘email’ query parameter
nextSearchParams.delete(“email”);
// Replace the URL with the updated query parameters router.replace(`${pathname}?${nextSearchParams}`);

}

How It Works

  1. Check for the Query Parameter: If email=true exists in the URL, the modal opens.
  2. Remove the Query Parameter: The email parameter is deleted from the query string using URLSearchParams.
  3. Update the URL: The router.replace() method replaces the current URL with the updated one, leaving the remaining query parameters intact.

Why Use These Hooks?

  • usePathname: Retrieves the current URL path without the query string.
  • useSearchParams: Provides easy access to query parameters in the URL.
  • useRouter: Allows seamless URL manipulation without triggering a page reload.

Conclusion

Using Next.js 14’s next/navigation utilities, you can easily manage query parameters to create smooth, dynamic interactions. This approach ensures your application remains user-friendly and avoids unnecessary page reloads.

Try this out in your Next.js 14 project and elevate your app’s interactivity!

Thank you for taking the time to read my post! If you have any questions or want to learn more about me and my work, feel free to reach out to me through my social media channels:

I’m always happy to connect and discuss ideas related to Blockchain, Web3 development, and technology in general. Looking forward to hearing from you!

--

--

No responses yet