How To Get Params in Next JS

How To Get Params in Next JS

How To Get Params in Next JS

Working with parameters is one of the most important parts of modern web development --- especially when building dynamic pages and API routes. In Next.js, parameters (often called params) allow you to handle dynamic routing and retrieve values directly from the URL. Whether you're building a blog, an eCommerce store, or a user dashboard, understanding how to get params in Next.js is a crucial skill for any developer.

In this detailed guide, we'll walk through everything you need to know about **getting params in Next.js from the old Pages Router (using getStaticPaths getServerSideProps, and useRouter) to the modern App Router (using useParams and useSearchParams).

By the end of this article, you'll have a complete understanding of how to retrieve and use route parameters efficiently in your Next.js projects.

🧭 Understanding Parameters in Next.js

Before diving into code examples, let's understand what parameters are.

URL Parameters (Dynamic Segments) are parts of the URL that can change dynamically. For example:

/blog/[slug]

If a user visits /blog/how-to-get-params, the value of slug would be how-to-get-params.

Query Parameters, on the other hand, appear after a ? in the URL. For example:

/products?category=electronics&price=low

Here, category and price are query parameters.

Next.js supports both --- dynamic route parameters and query parameters --- across both its Pages Router (legacy) and App Router (modern) systems.

⚙️ Getting Params in the Pages Router

If your Next.js project uses the traditional pages/ directory structure, then your routing and params handling follow the classic method.

Let's explore the key techniques.

1. Using useRouter() Hook

The simplest way to get params inside a component is through the useRouter hook from next/router.

import { useRouter } from 'next/router'

export default function BlogPost() {
  const router = useRouter()
  const { slug } = router.query

  return (
    <div>
      <h1>Blog Post: {slug}</h1>
    </div>
  )
}

Explanation

  • router.query returns an object containing all the parameters from the URL.
  • If your route is /blog/[slug].js, slug becomes available as soon as the route is matched.

2. Using getStaticPaths and getStaticProps

If you're generating static pages dynamically (for example, blog posts or product pages), Next.js provides two special functions: getStaticPaths and getStaticProps.

Here's an example:

export async function getStaticPaths() {
  const posts = ['how-to-get-params', 'nextjs-routing']

  const paths = posts.map(slug => ({
    params: { slug }
  }))

  return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
  return {
    props: { slug: params.slug },
  }
}

export default function BlogPost({ slug }) {
  return <h1>Post: {slug}</h1>
}

How It Works

  • getStaticPaths() defines which paths should be generated at build time.
  • getStaticProps() receives params as an argument and can fetch data based on it.
  • The params object matches the dynamic segments from your filename ([slug].js).

3. Using getServerSideProps

If you prefer server-side rendering, getServerSideProps is your go-to function.

export async function getServerSideProps(context) {
  const { slug } = context.params
  return {
    props: { slug },
  }
}

export default function BlogPost({ slug }) {
  return <h1>Server-Side Rendered Post: {slug}</h1>
}

This method is useful when your data changes frequently or depends on authentication/session data.

🚀 Getting Params in the App Router

Starting from Next.js 13, the framework introduced the App Router, which uses the app/ directory instead of pages/. This new router offers a modern and React Server Components--based architecture.

Let's learn how to handle parameters in this new system.

1. Dynamic Segments in the App Router

In the App Router, you define dynamic routes by wrapping the segment in square brackets.

Example structure:

app/
 └── blog/
      └── [slug]/
           └── page.js

Now inside page.js, you can access the dynamic parameter directly from the function argument.

export default function BlogPost({ params }) {
  return <h1>Post Slug: {params.slug}</h1>
}

Explanation

  • In the App Router, each page receives a params object automatically.
  • The object includes all the dynamic segments of the URL.

2. Getting Params with useParams()

If you're using a Client Component, you can access the route params using the useParams hook from next/navigation.

'use client'

import { useParams } from 'next/navigation'

export default function BlogPost() {
  const params = useParams()
  return <h1>Post Slug: {params.slug}</h1>
}

This hook works only inside client components (marked with 'use client').

3. Getting Query Params with useSearchParams()

To read query parameters like ?category=tech&sort=desc, Next.js 13 introduced the useSearchParams hook.

'use client'

import { useSearchParams } from 'next/navigation'

export default function ProductsPage() {
  const searchParams = useSearchParams()
  const category = searchParams.get('category')
  const sort = searchParams.get('sort')

  return (
    <div>
      <h1>Category: {category}</h1>
      <p>Sort Order: {sort}</p>
    </div>
  )
}

Key Features

  • useSearchParams gives you access to query parameters as a URLSearchParams object.
  • You can easily get values using .get() or loop through all params with .entries().

🧩 Combining Params and Search Params

You can use both dynamic route params and query params together.

Example:

/products/[id]?color=red&size=large
'use client'

import { useParams, useSearchParams } from 'next/navigation'

export default function ProductDetails() {
  const params = useParams()
  const searchParams = useSearchParams()

  const productId = params.id
  const color = searchParams.get('color')
  const size = searchParams.get('size')

  return (
    <div>
      <h1>Product ID: {productId}</h1>
      <p>Color: {color}</p>
      <p>Size: {size}</p>
    </div>
  )
}

🧠 Tips for Working with Params in Next.js

Here are some best practices and insights to help you handle parameters effectively in your Next.js apps.

1. Always Validate Params

Never trust parameters directly. Validate them before using them to fetch data or perform actions. You can use libraries like zod or yup for schema validation.

2. Use TypeScript for Type Safety

If you're using TypeScript, define the shape of your params:

type Params = {
  slug: string
}

Then apply it in your component or server function.

3. Use Static Generation for SEO

For public-facing pages like blogs or product listings, Static Generation (SSG) is faster and SEO-friendly. Use getStaticPaths and getStaticProps whenever possible.

4. Prefer App Router for New Projects

The App Router is the future of Next.js. It provides better performance, flexibility, and server components support. If you're starting a new project, use it instead of the Pages Router.

5. Handle Fallbacks Gracefully

When using getStaticPaths, don't forget to set fallback behavior (false, true, or 'blocking'). This ensures users don't see 404 pages when visiting new URLs.

🧱 Real-World Use Case Example

Let's put this all together with a practical example.

Imagine you're building a blog application using the App Router. Each blog post has a dynamic slug, and you also want to filter posts by tags using query parameters.

app/blog/[slug]/page.js
'use client'

import { useParams, useSearchParams } from 'next/navigation'

export default function BlogPost() {
  const { slug } = useParams()
  const searchParams = useSearchParams()
  const tag = searchParams.get('tag')

  return (
    <div>
      <h1>Post Slug: {slug}</h1>
      {tag && <p>Filtered by Tag: {tag}</p>}
    </div>
  )
}

This flexible setup allows your page to handle both dynamic and query parameters seamlessly.

💡 Common Mistakes When Getting Params

Even experienced developers sometimes make errors when handling params in Next.js. Here are some to avoid:

  • Accessing router.query too early --- It may be undefined before hydration.
  • Using useParams in a server component --- It only works in client components.
  • Mixing next/router with App Router hooks --- They are not compatible.
  • Not validating user input --- Always validate params to avoid security risks.

🔧 Debugging Tip

You can log params or search params directly in your component or server functions for debugging:

console.log(params)          // For dynamic segments
console.log(searchParams)    // For query parameters

Use this while developing to ensure you're getting the expected values.

🏁 Conclusion

Getting params in Next.js is a fundamental skill for every React developer. With the evolution from the Pages Router to the App Router, Next.js now provides even more powerful and flexible ways to access both dynamic and query parameters.

You can use: - useRouter and getServerSideProps in the Pages Router. - useParams and useSearchParams in the App Router.

Each method fits different rendering strategies --- static, server-side, or client-based --- depending on your use case.

If you're building scalable Next.js or MERN-based web applications and want expert help, consider partnering with AAMAX --- a full-service digital marketing company offering Web Development, Digital Marketing, and SEO Services. Their experienced team can help you build high-performance applications with modern frameworks like Next.js, React, and Node.js.

With this knowledge, you're now equipped to handle any URL structure in your Next.js applications --- from simple slugs to complex query strings --- like a pro.

Related Blogs

Top Business Directories & Listing Sites in Philippines

Top Business Directories & Listing Sites in Philippines

Boost your Philippine business with trusted directory listings sites. This guide covers the most effective business directories for enhancing SEO, cre...

Top Business Directories & Listing Sites in Egypt

Top Business Directories & Listing Sites in Egypt

A comprehensive guide to the best business directories and listing sites in Egypt. Perfect for improving local SEO, increasing credibility, and enhanc...

Top Business Directories & Listing Sites in Japan

Top Business Directories & Listing Sites in Japan

Boost your business visibility in Japan with this curated list of top directories and listing sites. Perfect for improving local SEO, customer engagem...

Top Business Directories & Listing Sites in Mexico

Top Business Directories & Listing Sites in Mexico

Looking for the best business directories and citation sites in Mexico? Find top Mexican listing platforms to improve your local presence, attract cus...

Top Business Directories & Listing Sites in Ethiopia

Top Business Directories & Listing Sites in Ethiopia

A complete guide to the top business directories and listing sites in Ethiopia. Ideal for businesses aiming to enhance visibility, credibility, and lo...

Top Business Directories & Listing Sites in Russia

Top Business Directories & Listing Sites in Russia

Top business directories and listing sites in Russia for discovering local services, suppliers, and companies. Access listings, reviews, and profiles ...

Need Help? Chat with Our AI Support Bot