2

Here is the situation... I have a Next.js app that has been up for a bit, we have a ton of code already writen.

Recently we started running some ads and we need to understand how they are doing...

Someone could land on our site with either of the two URLs.

www.site.com/page // user came to our site NOT from ad
www.site.com/page?ad=campaign1 // user came from one of our ads.

If a user comes to our site with the "ad" querystring, I would like to append that to ALL links on our site.

How would I go about doing that in react/nextjs? we have a ton of components already built and even some blog posts where we are just rendoring raw HTML.

Without going and editing a zillion components. How would I go about appending the query string to all links?

Thanks

1

1 Answer 1

0

You could create a custom Link component, as a wrapper to next/link, that would check for the query string and add it to the href of the Next.js Link.

// components/link.jsx

import NextLink from 'next/link';
import { useRouter } from 'next/router';

const Link = ({ children, href }) => {
  const router = useRouter();
  const [, queryString] = router.asPath.split('?');
  const hrefWithQuery = `${href}${queryString ? `?${queryString}` : ''}`;
  return <NextLink href={hrefWithQuery}>{children}</NextLink>;
};

export default Link;

Then replace all imports of next/link with the path to the new component wherever they are used (a simple search & replace would do).

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

2 Comments

There are some components (like the body of a blog post) that just have raw "dangerouslySetInnerHTML" content. How would you handle that?
Before setting it to dangerouslySetInnerHTML you could parse the raw HTML, look for links and modify their hrefs with the same logic as above. Can't think of a solution that doesn't involve parsing the HTML.

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.