useRouter/withRouter receive undefined on query in first render

It is not possible to get a query value at the first render.

Statically optimized pages are hydrated without provided route parameters. E.g. query is an empty object ({}).

After hydration, Next.js will fill the query object.

Also, at first render of a dynamic route router.asPath and router.route are equal. Once query object is available, router.asPath reflects it.

You can rely on the query value within a useEffect hook after asPath has been changed.

const router = useRouter();

useEffect(() => {
  if (router.asPath !== router.route) {
    // router.query.lang is defined
  }
}, [router])

GitHub Issue - Add a "ready" to Router returned by "useRouter"


In NextJS 9, one way to ensure route parameters are immediately available for page components is to get them from the context arg passed to getServerSideProps() and pass to the component as props.

For a page like [id].js,

export function getServerSideProps(context) {
  return {
    props: {params: context.params}
  };
}

export default ({params}) => {
  const {id} = params;
  return <div>You opened page with {id}</div>;
};

Tags:

Next.Js