The Hidden Pitfalls of the Next.js Link on Website Speed

The tale of the "Reduce unused Javascript"
I entered one of my Next.js website URLs into Google's PageSpeed Insights page, and I noticed the Reduce unused JavaScript message being flagged and pointing to an especially large-sized chunk. I ran the Next.js Bundle Analyzer on my website to investigate the chunk. The result was very surprising to me. The chunk contained the code for an imported video player library which was not being used at all on the page. Then, I looked at all of the other chunks, and they also contained code for imported libraries which were not being used on the homepage. In the screenshot above, there is 600kb of unused Javascript that is not directly being used on the homepage, which is negatively affecting my website's Core Web Vitals.
I went through the following process to discover why this might be happening:
- I commented out all of the code on the Next.js page
- I added each React component back in a piecemeal fashion
- I checked the Network tab in the Chrome DevTools to inspect which chunks were being downloaded as I added each React component back in
There was one particular React component that triggered the unnecessary chunk download when it was added back in: the Next.js Link component.
The Next.js Link component prefetches your pages
It turns out that using the Next.js Link component will automatically prefetch the page you link to when you use the href prop. This component has an optional prop called prefetch which is set to be true by default. I have summarized the prefetch behavior in the following points:
- Pages will be prefetched if there is a Link component pointing to that page, and the Link component is visible in the current viewport
- Pass prefetch={false} to disable any prefetching
- Pages will still be fetched on hover even if you disable prefetch
Conclusion
In my case, my Next.js homepage used the Link component to link to a video page which imported a video player library, which is why the chunk was being downloaded on the homepage. To ensure the homepage would not download unused Javascript, I set prefetch={false} because it was a premature optimization for this case.
Would I universally prescribe that you turn off prefetching for all Links? In this particular case, the video player library was many hundreds of kilobytes and not every user would play a video, so I opted to turn off prefetching. If you link to a page is loading a chunk that is relatively small, and most of your users are expected to load that page, then using the default behavior will give your user a smoother experience.
In a future post, I will go over the process of how to use the Next.js Bundle Analyzer to fix the Reduce unused JavaScript warning and improve your performance in the Core Web Vitals.