How to solve router.query is undefined in Next.js

Cover Image for How to solve router.query is undefined in Next.js
Ali Bentaleb

router.query is an object returned in next.js containing the query string. Sometimes it can return undefined while rendering especially in first render. To solve this issue, wrap router.query in react useEffect hook and control its rendering using router.isReady like this useEffect(()=>{… if(router.isReady) router.query…},[router.isReady])

In this tutorial, we are going to show in details how you can do this

Use router.query

First, to use router.query, we need to create an instance from next useRouter like this:

Create pages/test.js

import {useRouter} from 'next/router';
export default function Test() {
	const router = useRouter();

	const {user} = router.query;
	console.log(user);

	return <p>User is {user}</p>;
}

Now to test it, hit http://localhost:3000/test?user=tom

You should see in the console something like this

router query undefined

As you can see in the console, the first render went undefined, and then in the second render we can see clearly the user has been logged

UseEffect to render router.query

Now let’s see how to render router.query and avoid the undefined error

To do it we are going to use useEffect hook and control the render when it is rendered with router.isReady

router.isReady is a boolean provided by default in next useRouter instance and it is true when the router is ready on client side for use

The final code will look like this:

Under pages/test.js

import {useRouter} from 'next/router';
import {useEffect} from 'react';

export default function Test() {
	const router = useRouter();

	const {user} = router.query;
	useEffect(() => {
		if (router.isReady) console.log(user);
	}, [router.isReady]);

	return <p>User is {user}</p>;
}

Run it the same way as previously and you will notice that now there is no undefined as the image below is showing:

router query with useEffect and router.isReady

Conclusion

We have seen how to solve router.query is undefined in Next.js

I recommend also to check to add query params to url in this link

How to add query params to Nex...How to set x-hasura-admin-secr...