Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

What is NextJs prefetching and why should I care

Let's say you have a NextJs site with an index.js page that links to an about page and contact page:

import Link from 'next/link'
export default () => (<div>
        <h1>My Index page</h1>
        <nav>
        <Link href='/contact'>Contact</Link>
        <Link href='/about'>About</Link>
        </nav>
</div>)

Out of the box the NextJs framework will search for the Link tags and will preload and render the linked pages. So, when user decides to click a link like<Link href="/contact"> the transition to the target page will be blazing fast. This the prefetching functionaliaty in NextJs.

Some notes on prefetching:

  • it only works just for the local internal pages of the current site. For example, if we have <Link href="https://www.google.com/"> the google.com page will not be prerendered so the transition will be slower
  • initilay, only the pages that have links in the visible viewport will be prerendered. NextJs will watch as the user scrolls and brings new links into the viewport and wil prerender the content for those pages as their links apper on the screen
  • the Nextjs prefetching will work only if you use the <Link> tags. Using the plain old <a> will not trigger a prerender. In general, it's not a good ideea to use them in Next
  • you can disable the prefeching of link by setting the prefetch atrribute: <Link href='/index' prefetch={false}>
  • what if the user press the back button? Nothing new will be loaded, because the browser still has the old index.js bundle in place, ready to load the /index route. It's all automatic. Of course this assume that index is a local page of the current site.
  • if the server sends the save-data HTTP header Nextjs prefetching will not work
  • the prefetching behavior is only being triggered in production mode. In order to see it in action be sure to stop the app if in development mode (npm run dev) and run npm run build and npm run start to use the production bundle
Home Screencasts Best of Newsletter Search X