How To Get Query Params in Next JS

How To Get Query Params in Next JS

How To Get Query Params in Next JS

Working with query parameters is a common task in modern web development. In Next.js, handling query strings efficiently can make your app dynamic, flexible, and SEO-friendly. Whether you’re building a blog, an eCommerce store, or a complex dashboard, understanding how to get query params in Next.js is essential for passing and reading data between routes.

In this comprehensive guide, we’ll explore different ways to get query parameters in Next.js, including both Pages Router and App Router approaches. By the end, you’ll know exactly how to extract, manipulate, and use query params in your Next.js applications.

🧭 Understanding Query Parameters

Query parameters are part of the URL that pass small pieces of data to your web application. They come after a ? symbol and are separated by &.

For example:

https://example.com/products?category=shoes&color=black

In this example, the query parameters are:

  • category = shoes
  • color = black

These parameters are often used for filtering, searching, or passing state data between pages.

⚙️ Getting Query Params in Next.js (Pages Router)

If you are using the Pages Router (available up to Next.js 12/13 with /pages directory), you can easily access query params using the useRouter hook from next/router.

Example: Using useRouter

import { useRouter } from 'next/router';

export default function ProductPage() {
  const router = useRouter();
  const { category, color } = router.query;

  return (
    <div>
      <h1>Product Category: {category}</h1>
      <p>Color Filter: {color}</p>
    </div>
  );
}

How it works

  • The useRouter hook gives access to the router object.
  • router.query holds all query parameters as key-value pairs.
  • If the page URL is /products?category=shoes&color=black, then:
    router.query = { category: "shoes", color: "black" };
    

🧩 Handling Query Params on the Server Side

Sometimes, you need to handle query parameters on the server for pre-rendering or data fetching.

Using getServerSideProps

You can access query params directly from the context object.

export async function getServerSideProps(context) {
  const { category, color } = context.query;

  return {
    props: {
      category,
      color,
    },
  };
}

export default function ProductPage({ category, color }) {
  return (
    <div>
      <h1>Category: {category}</h1>
      <p>Color: {color}</p>
    </div>
  );
}

Why use this method?

  • Ideal for SEO and server-side rendering (SSR).
  • Useful when fetching data from an API that depends on the query params.

🚀 Getting Query Params in Next.js (App Router)

In the App Router introduced with Next.js 13+, the approach is different. Instead of next/router, you use hooks from the next/navigation module.

Example: Using useSearchParams

'use client';

import { useSearchParams } from 'next/navigation';

export default function ProductPage() {
  const searchParams = useSearchParams();
  const category = searchParams.get('category');
  const color = searchParams.get('color');

  return (
    <div>
      <h1>Category: {category}</h1>
      <p>Color: {color}</p>
    </div>
  );
}

How it works

  • The useSearchParams hook returns a URLSearchParams object.
  • You can call .get('key') to retrieve specific parameters.
  • Great for client-side rendering scenarios.

🧠 Accessing Query Params on the Server in App Router

For server components, you can get query parameters from the searchParams prop in your page function.

Example:

export default function ProductPage({ searchParams }) {
  const category = searchParams.category;
  const color = searchParams.color;

  return (
    <div>
      <h1>Category: {category}</h1>
      <p>Color: {color}</p>
    </div>
  );
}

When to use

  • This is the recommended way to access query params in server components.
  • Ideal for SEO-friendly pages that use server-side rendering (SSR) or static site generation (SSG).

🔁 Updating Query Params in Next.js

You might also need to add, update, or remove query parameters dynamically based on user interactions.

Example: Updating query params using useRouter (Pages Router)

import { useRouter } from 'next/router';

export default function FilterButton() {
  const router = useRouter();

  const handleFilter = () => {
    router.push({
      pathname: '/products',
      query: { category: 'shoes', color: 'red' },
    });
  };

  return <button onClick={handleFilter}>Filter Shoes</button>;
}

This updates the URL to /products?category=shoes&color=red without reloading the page.

Example: Updating Query Params in App Router

'use client';

import { useRouter, useSearchParams } from 'next/navigation';

export default function FilterButton() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const handleFilter = () => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('category', 'shoes');
    params.set('color', 'red');
    router.push(`/products?${params.toString()}`);
  };

  return <button onClick={handleFilter}>Filter Shoes</button>;
}

This method ensures the new query params are reflected instantly in the browser’s address bar.

🧩 Combining Dynamic Routes and Query Params

Next.js also allows combining dynamic routes with query params. For example:

  • Dynamic route: /products/[id].js
  • URL: /products/123?ref=homepage
import { useRouter } from 'next/router';

export default function ProductDetail() {
  const router = useRouter();
  const { id, ref } = router.query;

  return (
    <div>
      <h1>Product ID: {id}</h1>
      <p>Referred from: {ref}</p>
    </div>
  );
}

This makes it easy to handle both path-based and query-based parameters together.

🔐 Type Safety with TypeScript

If you’re using TypeScript, you can make your query parameters type-safe.

import { useRouter } from 'next/router';

interface QueryParams {
  category?: string;
  color?: string;
}

export default function ProductPage() {
  const router = useRouter();
  const query = router.query as QueryParams;

  return (
    <div>
      <h1>Category: {query.category}</h1>
      <p>Color: {query.color}</p>
    </div>
  );
}

This prevents type errors and improves code maintainability.

⚡ Common Mistakes to Avoid

  1. Accessing query params too early — The router may not be ready immediately on first render. Always check router.isReady before accessing router.query.
  2. Not encoding query params — Use encodeURIComponent() for values that may contain spaces or special characters.
  3. Mixing client and server hooks — Use useRouter in client components and searchParams in server components.
  4. Ignoring URL updates — Query parameters do not trigger re-renders automatically; you may need to use state or effect hooks to respond to changes.

🧩 Practical Use Cases for Query Params

  • Filtering products (?category=shoes&size=10)
  • Pagination (?page=2)
  • Sorting (?sort=price_asc)
  • Search results (?q=smartphones)
  • Tracking referrals (?ref=google)

🛠️ Tools and Libraries for Better Query Param Handling

You can enhance your query parameter management using helper libraries like:

  • query-string – for parsing and stringifying query params.
  • URLSearchParams – native JavaScript API for managing search parameters.
  • Next.js useSearchParams – built-in hook for Next 13+.

Example using query-string:

npm install query-string
import queryString from 'query-string';

const parsed = queryString.parse(window.location.search);
console.log(parsed); // { category: 'shoes', color: 'black' }

💡 Final Thoughts

Understanding how to get and manage query params in Next.js is essential for creating dynamic, data-driven applications. Whether you’re using the traditional Pages Router or the modern App Router, Next.js provides multiple hooks and utilities to make this task straightforward and efficient.

If you’re building a scalable Next.js or MERN Stack application and need professional help, consider AAMAX. AAMAX is a full-service digital marketing and web development company specializing in MERN Stack Development, Digital Marketing, and SEO Services.

With their experienced developers and marketers, you can bring your web project to life—optimized for performance, usability, and visibility.

🚀 Key Takeaways

  • Use useRouter for query params in the Pages Router.
  • Use useSearchParams or searchParams prop in the App Router.
  • For server-side rendering, use getServerSideProps or server components.
  • Always encode and validate query parameters.
  • Combine dynamic routes with query params for more flexible navigation.

With these tools and techniques, you’re ready to confidently handle query parameters in your Next.js applications and build user-friendly, data-rich experiences.

Related Blogs

How To Run React JS App

How To Run React JS App

React is ideal for developers who want speed, flexibility, and high performance. It integrates seamlessly with RESTful APIs and backend frameworks. It...

How To Route to a Page in Next JS

How To Route to a Page in Next JS

In this article, we’ll cover everything you need to know about routing in Next.js — from the basics of file-based routing to advanced dynamic and API ...

How To Get Query Params in Next JS

How To Get Query Params in Next JS

Understanding how to get and manage query params in Next.js is essential for creating dynamic, data-driven applications. Whether you’re using the trad...

How To Install Next JS

How To Install Next JS

Their experienced team ensures pixel-perfect designs, scalable backend systems, and SEO-friendly code structure — perfect for startups, small business...

How To Run Next JS App

How To Run Next JS App

Running a Next.js app efficiently involves understanding its different modes — development, production, and server environments. Whether you’re testin...

How To Import Image in Next JS From Public Folder

How To Import Image in Next JS From Public Folder

Next.js combines the simplicity of React with built-in performance optimization tools. Its Image component and static asset management through the pub...

Need Help? Chat with Our AI Support Bot