Search code examples
javascriptnext.jsnext-router

Next.js Link "as" decorator stopped working for dynamic routes?


I have a dynamic route:

test/[id].js

When user clicks on a link pointing to /test/1 Next.js ends up rendering the proper page as intended.

The funny business starts when I want to have /test/1 url masked with anything else.

<Link href="/test/1" as="/any/thing/here">

As far as I understand the above code should:

  • move user to test/1 and render test/[id].js,
  • hide the domain.com/test/1 url behind domain.com/any/thing/here.

What happens is it does not point to test/[id].js at all, just returns a 404.

Sandbox link with broken code:

https://codesandbox.io/s/nervous-silence-z62s1?file=/pages/index.js

What am I doing wrong here? I have a really long and complex urls with lots of slashes I have to use with Next.js dynamic routing, and I don't see any other solution than using "as"... I'm pretty much sure I used to use it a few years back and it just worked! Seems like it worked for this guy as well: Linking to dynamic routes in Next.js

If Next.js changed something then how I recreate this functionality easily?


Solution

  • I think you need to write href like that:

          <Link
            href="/test/[id]?id=1"
            // Or like that
            href={{
              pathname: '/test/[id]',
              query: { id: '1' }
            }}
            as="/any/thing/here"
          >
            <a>Link to test/1 - 'as' decorator is broken?</a>
          </Link>
    

    I am not sure why it works like that, but I saw it somewhere some time ago and I use it like that since then. I think there is no information about it in the docs.

    And be sure that /any/thing/here page actually exists too, because otherwise if user refresh browser after client side navigation there will be 404 anyway.