Zach Schnackel

Improving Next.js links

Next 13 changes how links are constructed; by not requiring the inner <a /> anymore 🎉

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.

index.tsx

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:

TextLink.tsx

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 href for non-http protocols

  • Attaches rel="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.

:: Published Jan 5, 2021 ::