0
0
NextjsHow-ToBeginner · 4 min read

How to Get Route Params in Next.js: Simple Guide

In Next.js, you get route parameters by defining dynamic routes with square brackets in the file name, like [id].js. Inside the component, use the useRouter hook from next/router to access router.query, which holds the route params.
📐

Syntax

To get route params in Next.js, create a dynamic route file using square brackets for the param name. Then use the useRouter hook to read the params from router.query.

  • pages/posts/[id].js: Defines a dynamic route with param id.
  • const router = useRouter(): Gets the router object.
  • router.query.id: Accesses the id param value.
javascript
import { useRouter } from 'next/router'

export default function Post() {
  const router = useRouter()
  const { id } = router.query

  return <p>Post ID: {id}</p>
}
Output
Post ID: 123 (if URL is /posts/123)
💻

Example

This example shows a page at pages/products/[productId].js that reads the productId from the URL and displays it.

javascript
import { useRouter } from 'next/router'

export default function Product() {
  const router = useRouter()
  const { productId } = router.query

  if (!productId) return <p>Loading...</p>

  return <div>
    <h1>Product Details</h1>
    <p>Product ID: {productId}</p>
  </div>
}
Output
<h1>Product Details</h1><p>Product ID: 456</p> (if URL is /products/456)
⚠️

Common Pitfalls

  • Trying to access router.query before the router is ready causes undefined params. Always check if params exist before using.
  • Using static routes instead of dynamic file names means no params are captured.
  • For server-side rendering, use getServerSideProps or getStaticProps to get params instead of useRouter.
javascript
import { useRouter } from 'next/router'

export default function Page() {
  const router = useRouter()
  // Wrong: directly using param without check
  // const { id } = router.query
  // return <p>ID: {id.toUpperCase()}</p> // Error if id is undefined

  // Right way:
  const { id } = router.query
  if (!id) return <p>Loading...</p>

  return <p>ID: {id.toUpperCase()}</p>
}
Output
Loading... (while param is undefined), then ID: ABC (if URL is /page/abc)
📊

Quick Reference

  • Define dynamic route files with [param].js.
  • Use useRouter from next/router to access router.query.
  • Check if params exist before using them.
  • For server-side data fetching, use getServerSideProps or getStaticProps.

Key Takeaways

Use dynamic route files with square brackets to define route params in Next.js.
Access route params inside components with the useRouter hook and router.query.
Always check if route params exist before using them to avoid errors.
For server-side rendering, get params via getServerSideProps or getStaticProps instead of useRouter.
Dynamic routes enable clean URLs and easy param access in Next.js apps.