1

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?

3 Answers 3

4

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

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.