If you ever tried to get query params from next/router
in useEffect
, you probably have this similar issue which the params are undefined. A simple example would be something like this:
Notice the data
is undefined on the console, but it is rendered on the DOM.
WHY?
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.
Which means, the useEffect
shown in the example above is triggered before hydration, thus the query is an empty object at that moment.
Solution Starting from NextJS@10.0.5
NextJS provides a boolean called isReady
in useRouter()
.
isReady
:boolean
- Whether the router fields are updated client-side and ready for use. Should only be used inside ofuseEffect
methods and not for conditionally rendering on the server.https://nextjs.org/docs/api-reference/next/router#router-object
All you have to do is to use router.isReady
like so in useEffect
Solution Before NextJS@10.0.5
If you’re using an older version of NextJS, you can use URLSearchParams
with window.location.search
to get query params.
const urlSearchParams = new URLSearchParams(window.location.search) const data = urlSearchParams.get('data')
A complete example is shown below.
Notice that window.location.search
has to be called inside the useEffect
as window
is not available on server-side.