How to interpolate query string on NextJS

Total
0
Shares

I am using the next/link to direct to a particular page. The link component looks like this:

<Link
    href={{
      pathname: `/users/[slug]?lang=${lang}`,
      query: { slug, lang },
    }}
>
 Click me
</Link>

The lang is the selected language (i18) of the user.

Problem

Every time I reach the page in question, after refreshing I am getting this error:

Error: The provided "href" (/users/[slug]?lang=en) value is missing query values (slug) to be interpolated properly. Read more: https://err.sh/vercel/next.js/href-interpolation-failed

Yet my URL looks like this http://localhost:3000/users/Y0901083155?lang=en
where the slug is Y0901083155 and the lang is en

Pages architecture

├──_app.js
├──index.js
├──user/ --------------> folder
   ├──[slug]/ --------> folder
      ├── edit/    ----> folder
      ├── create/  ----> folder
      ├── index.tsx

Solution

You should include the slug in the pathname and pass lang in the query object.

// Assuming slug='some-slug', and lang='en'

<Link
    href={{
        pathname: `/users/${slug}`, // Will match `/users/some-slug` path
        query: { lang } // Will pass `?lang=en` as query param
    }}
>
    Click me
</Link>
Leave a Reply

Your email address will not be published. Required fields are marked *