Chris
Chris

Reputation: 668

Accessing URL params in "href" when using "as" for Next Link?

I have a Link where I want to pass certain params in the URL but I don't want the browser to display the params.

I'm using Link's as for this:

<Link href={`/link?foo=bar`} as ={`/link`}>
  <a>Link</a>
</Link>

But when I click this link and I try to access the params via router, I can't access foo=bar:

const router = useRouter()
console.log(router.query)

Returns

{
  slug: ["link"],
}

And not

{
  slug: ["link"],
  foo: "bar",
}

So how can I access the URL params in href when using as for Link?

Upvotes: 2

Views: 2055

Answers (1)

tenshi
tenshi

Reputation: 26404

TL;DR You can't use as like that.

This is an incorrect usage of href and as. It would be cool if we could hide state from the end users to keep our URLs nice, clean, and compact, but obviously if you do that, you'll actually lose the state when copy/pasting the URL. That's why you can't hide query parameters in anyway (except for excluding them).

Here's the docs on href and as (dynamic routes, has little to do with hiding query params):

https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes

And to further bring up my point, imagine if we could hide state, and we redirect to this URL:

https://example.com/stateful/

Presumably there would be some behind-the-scenes browser action that persists the state.

Now we copy/paste the URL:

https://example.com/stateful/

Oops! We don't have the state anymore because the browser has no previous state to keep track of! That's why you use query parameters, because they keep the state in the URL itself.

Upvotes: 3

Related Questions