/

Prefetching Content in Next.js

Prefetching Content in Next.js

In this article, we will explore how prefetching works in a Next.js app and how it can optimize the loading speed of your website.

When using the Link component in Next.js to create links between pages, Next.js handles frontend routing seamlessly. When a user clicks on a link, the frontend updates the page without triggering a new client/server request and response cycle, which is typical for web pages.

But there’s more to Next.js when it comes to link handling.

Next.js also prefetches the URL pointed to by an element wrapped within the <Link> component as soon as it appears in the viewport. This behavior occurs only in production mode and for local links within the website. By prefetching the content, Next.js ensures a super-fast browsing experience for the viewers.

To activate this prefetching feature, you need to run the application in production mode. This means stopping the application if you are running it with npm run dev, compiling the production bundle with npm run build, and then starting it with npm run start.

To observe the prefetching in action, you can use the Network inspector in the DevTools. You will notice that any links visible above the fold at page load trigger prefetching as soon as the load event fires on your page. The load event indicates that the page is fully loaded and occurs after the DOMContentLoaded event.

For links that are not in the viewport initially, Next.js will prefetch them when the user scrolls and they come into view.

Prefetching is automatic on high-speed connections like WiFi and 3G+ unless the browser sends the Save-Data HTTP Header, which opts out of prefetching.

If you want to opt out from prefetching for specific Link instances, you can set the prefetch prop to false:

1
2
3
<Link href="/a-link" prefetch={false}>
<a>A link</a>
</Link>

In conclusion, Next.js provides automatic prefetching of local links within your app, improving the loading speed and enhancing the user’s browsing experience. Make sure to use it wisely and consider disabling prefetching for specific links when necessary.

Tags: Next.js, prefetching, frontend routing, optimization