Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRouter - query object is empty

i'm trying to learn routing in Next.JS but I can't manage to get the query object.

File path: ./src/pages/[test]/index.tsx

import { useRouter } from 'next/router';

export default function Test() {
  const router = useRouter();
  console.log(router.query);
  return (
    <div>
      <h1>Test</h1>
    </div>
  )
}

console.log just prints {}

like image 873
Raphael Jayme Avatar asked Jun 14 '26 13:06

Raphael Jayme


1 Answers

If your page is a dynamic route, and you expect query to have route parameters in it, It is expected to have it empty during pre-rendering phase if your page is statically optimized by Automatic Static Optimization.

Quoting from documentation

Pages that are statically optimized by Automatic Static Optimization will be hydrated without their route parameters provided, i.e query will be an empty object ({}).

After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object.

It is possible to watch the query in useEffect like following;

useEffect(() => {
  console.log(router.query);
}, [router.query]);
like image 87
choz Avatar answered Jun 18 '26 00:06

choz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!