4

I'm used Next.js but i have an error with dynamic route.

In my application I use getStaticPaths, getStaticProps and this:

<Link
    href={`/offers/[id]?id=${offer.id}`}
    as={`/offers/${offer.id}`}
>
    <a>{offer.title}</a>
</Link>

When I click on this link, I have no problem with the dynamic route to display my page.

But when I refresh the same page, I get this message:

enter image description here

When I looked for a solution the answer was that my Link did not have the right setting when clicked on.

But now I don't click on the link, I just refresh my page.

I use Next.js 10.0.7

juliomalves
  • 42,130
  • 20
  • 150
  • 146
jean A
  • 41
  • 1
  • 2

2 Answers2

4

Since Next.js 9.5.3 there's no longer the need to use as for dynamic routes. Instead you can directly use the value to interpolate in href.

<Link href={`/offers/${offer.id}`}>
    <a>{offer.title}</a>
</Link>

Alternatively, you can also use a different Link syntax by passing a URL object to it.

<Link
    href={{
        pathname: '/offers/[id]',
        query: { id: offer.id }
    }}
>
    <a>{offer.title}</a>
</Link>
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    Hello, thank you for your answer but I still have the same problem. My link works fine, the problem comes from the reloading of the page every time I refresh it gives me this error. – jean A Mar 29 '21 at 10:42
  • And you still get the same error even with the change I suggested? – juliomalves Mar 29 '21 at 11:01
  • hello yes but I try several changes to see if it comes from my code if i find a solution or an answer of my problem i can post it. – jean A Mar 31 '21 at 15:45
  • @jeanA Does your link still work? Neither of mine, link or page refresh, works. The same error is thrown. Have any idea? – Sunday Power Inemesit Jan 13 '22 at 01:47
3

I had a similar problem. But I've been working with translations on the website.

So when I change selected language on any page it works fine, but as soon as I change language on any of the [id] page (item, article, etc.) I got the same error as you have.

In my case the problem was inside router.push() method I've used. So when I pass router.pathname it returns /articles/[id] literally.

But actually I needed to use router.asPath which returns the correct URL path, such as /articles/abc123-456zczxc-7890-blablabla.

Here is an example from NextJS docs:

pathname: String - Current route. That is the path of the page in /pages, the configured basePath or locale is not included.

asPath: String - The path (including the query) shown in the browser without the configured basePath or locale.

NextJS API Reference Link

Dylan_Gomes
  • 2,066
  • 14
  • 29