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](https://aamax.co/service/nextjs-web-development#place-order)** 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`
```javascript
import { useRouter } from 'next/router';
export default function ProductPage() {
const router = useRouter();
const { category, color } = router.query;
return (
);
}
```
### 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:
```js
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.
```javascript
export async function getServerSideProps(context) {
const { category, color } = context.query;
return {
props: {
category,
color,
},
};
}
export default function ProductPage({ category, color }) {
return (
);
}
```
### 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`
```javascript
'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 (
);
}
```
### 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:
```javascript
export default function ProductPage({ searchParams }) {
const category = searchParams.category;
const color = searchParams.color;
return (
);
}
```
### 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)
```javascript
import { useRouter } from 'next/router';
export default function FilterButton() {
const router = useRouter();
const handleFilter = () => {
router.push({
pathname: '/products',
query: { category: 'shoes', color: 'red' },
});
};
return ;
}
```
This updates the URL to `/products?category=shoes&color=red` without reloading the page.
### Example: Updating Query Params in App Router
```javascript
'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 ;
}
```
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`
```javascript
import { useRouter } from 'next/router';
export default function ProductDetail() {
const router = useRouter();
const { id, ref } = router.query;
return (
);
}
```
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.
```typescript
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 (
);
}
```
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`:
```bash
npm install query-string
```
```javascript
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](https://aamax.co)**. 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.
Product Category: {category}
Color Filter: {color}
Category: {category}
Color: {color}
Category: {category}
Color: {color}
Category: {category}
Color: {color}
Product ID: {id}
Referred from: {ref}
Category: {query.category}
Color: {query.color}
Grow Your Reach
Want to publish a guest post on aamax.co?
Place an order for a guest post or link insertion today.
Place an Order