How to push params with next/router in Next.js

Cover Image for How to push params with next/router in Next.js
Ali Bentaleb

In Next.js, useRouter from next/router let you push URL with params and use them later.

To push params using next/router, create an instance of router using useRouter(), and assign your params to query like this: router.push({ query: { urlparam: “value” } })

the final code will look like:

Create pages/test.js

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

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

	useEffect(() => {
		router.push({query: {param: 'value'}});
	}, [router.isReady]);

	return <div>Hello</div>;
}

What we have done is create an instance of next router using useRouter

useEffect is used so that rendering will be done on client side since params are accessible only on client side

With router.isReady, we are making sure that re rendering will be done again once the next/router is available for use so that we can access params at that time

Then we assign our params to query property using push method provided by the router

Second method

You can also use the syntax router.query.param=“value” to assign params directly and push again the router

Let’s see an example :

under pages/test.js

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

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

	useEffect(() => {
		router.query.param = 'value';
		router.push(router);
	}, [router.isReady]);

	return <div>Hello</div>;
}

Test configuration

Run your server and hit localhost:3000 or whatever port you are using for dev server

next router push params image

As you can see on the url, the params are pushed correctly with the first or the second method

Conclusion

We have seen how to use next/router to push url with params

I recommend to check also these articles regarding next/router so that you learn interesting tricks of next router to use on your app:

How to get previous URL with next/router

How to append params to next/router

How to get query params in Next.js

How to display Mui TextField v...How to use nivo charts with Ne...