5

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.

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38

2 Answers2

4

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.

paulin-crtn
  • 325
  • 2
  • 9
3

as props works fine with next/link and you can hide query parameters with next/link as well:

<Link
  href={`/blogs/${item.slug}?id=${item.id}`}
  as={`/blogs/${item.slug}`}
  passHref
>
  <a href="" className="hover:text-cyanBlue">
    Read More
  </a>
</Link>

But keep in mind, this won't work if you set target="_blank" to anchor tag, or open link to the next tab of browser.

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
Anurag Tripathi
  • 784
  • 1
  • 13
  • 13