Dynamic route not working on page refresh with Next.js

Viewed 2644

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

2 Answers

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>

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

Related