Next.js router is returning query parameters as undefined on first render?

Just found out what is the solution to my problem:

From: https://nextjs.org/docs/api-reference/next/router#router-object

isReady: boolean – Whether the router fields are updated
client-side and ready for use. Should only be used inside of
useEffect methods and not for conditionally rendering on the server.

This is what happens to the router.query on client when you hit /search?q=XXX.

1st render

router.isReady: false
router.query: {}

Subsequent renders

router.isReady: true
router.query: {"q":"xxx"}

Conclusion

The fact that router.query is not populated on the client (for SSG pages) on the first run is a design implementation detail. And you can monitor whether it’s has been populated or not by checking the router.isReady boolean property.

Leave a Comment