Search code examples
reactjsnext.jsnext-router

How to pass data with next router without showing it in the URL?


I am using next router and I want to pass data to another page but I don't want the data to be shown in the URL

I have a button once clicked it redirects to another page and pass an object myObject to it.

const router = useRouter();
const myObject = {
  proprety1: "example1",
  proprety2: "example2",
  proprety3: "example3",
}
//...
<button
   onClick={() => {
     router.push({
       pathname: "/next-page",
       query: { data: JSON.stringify(myObject) },
     });
   }}
 >
   Navigate
</button>

Then in next-page I get this as URL :

http://localhost:3000/next-page?data=%7B"proprety1"%3A"example1"%2C"proprety2"%3A"example2"%2C"proprety3"%3A"example3"%7D

This works fine to be clear, but it is really ugly, not just that, I don't want data to be shown to users in the url.


Solution

  • I believe you can use the second parameter as in the router.push function in order to accomplish what you want.

    router.push(url, as, options)

    See documentation.