Improving Next.js links

January 5, 2021

Next.js ships with a <Link /> component, available via the next/link module. Both client-side transitions and preloading routes make this a must-have for fast user experiences.

One aspect that's always looked a bit odd to me is how the DOM is constructed. Ideally, I'd prefer something more familiar with the ability to choose between both internal and external links.

Similar to a previous article on MDX link routing in Gatsby, it turns-out we can use a very similar approach in Next.js:

The above <TextLink /> component accomplishes the simplicity I was after by doing the following:

  • Updates any absolute links that match our domainRegex and makes them relative

  • Returns next/link as the link component for any relative links

  • Returns a normal ahref for non-http protocols

  • Attaches target="_blank" rel="noopener noreferrer nofollow" for external links that match none of the above

  • Best of all, I can write my links as I normally would, with all props passed-through to their appropriate areas:

I also use this as part of the components I pass-through to next-mdx-remote to transform Markdown links automatically.