I'm facing an issue while trying to access query parameters in Next.js 13 using the useRouter hook. When I run the following code
'use client'
import { useRouter } from 'next/navigation';
const Post = () => {
    const router = useRouter();  
    
    return (
        <div>
            post number : {router.query.id}
        </div>
  )
}
export default Post
I receive the following error:
Unhandled Runtime Error
TypeError: router.query is undefined
Source
  25 |   return (
  26 |       <div>
> 27 |           post number : {router.query.id}
     |                         ^
  28 |       </div>
  29 | 
  30 | )
i take the code from the official website Routing:Dynamic Routes,
you can look here
i log it in the console to see what inside the variable router, i get this this
I encountered the issue while trying to access query parameters using the useRouter hook from next/router inside the app directory in Next.js. After referring to the Next.js documentation
This can also happen when you try to use the useRouter hook from next/router inside the app directory, as the App Router's useRouter from next/navigation has different behavior to the useRouter hook in pages.
To resolve this issue, you can make use of the useParams hook from the next/navigation package. This hook provides a solution for getting URL params , without relying on useRouter.
Here's an example of the modified code that successfully access query parameters:
'use client'
import { useParams } from 'next/navigation';
const Post = () => {
  const { id } = useParams();
  return (
    <div>
      Post number: {id}
    </div>
  );
}
export default Post;
By using useParams, you can directly destructure the id parameter from the route and utilize it within your component.
Keep in mind that the example code assumes you are using the latest version of Next.js (v13.4.6).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With