最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can not add query params to the nextjs dynamic route - Stack Overflow

programmeradmin2浏览0评论

I have file named. [slug].js.

what I am trying to do is that I want to add query parameter to this dynamic route, this is the code.

   await router.replace({
          pathname: `${router.pathname}`,
          query: { coupon },
        },
        undefined,
        { shallow: true });

This works fine every static page but on dynamic page it gives me this error:

Error: The provided `href` (/home/[slug]?theme=dark) value is missing query values (slug) to be interpolated properly. Read more: .js/href-interpolation-failed

any suggestions please?

I have file named. [slug].js.

what I am trying to do is that I want to add query parameter to this dynamic route, this is the code.

   await router.replace({
          pathname: `${router.pathname}`,
          query: { coupon },
        },
        undefined,
        { shallow: true });

This works fine every static page but on dynamic page it gives me this error:

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

any suggestions please?

Share Improve this question asked Feb 16, 2022 at 15:41 Nicholas BravesonNicholas Braveson 151 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

@Ghader's answer in in the correct direction, but inplete:

router.replace(
  {
    pathname: router.asPath.split('?')[0],
    query: { coupon },
  },
  undefined,
  { shallow: true }
);

You need to remove query parameters from the pathname as otherwise, you are going to get double encoded URLs.

Use router.asPath to get current page path without query string :

router.replace({
          pathname: router.asPath,
          query: { coupon },
        },
        undefined,
        { shallow: true });

If you're just adding query parameters to the current path, you can pletely omit the pathname field from the URL object.

router.replace(
    { query: { coupon } },
    undefined,
    { shallow: true }
);
发布评论

评论列表(0)

  1. 暂无评论