Skip to content
Advertisement

How to prefetch code for multiple pages from one page request in Next.js?

Using client-side navigation I can navigate between pages using only JavaScript. The first request of a page takes some time to render and then the navigation back to it is nearly instant. During that first render that page only loads what’s necessary for it. That isolates each page making them independent. I just want to know, if there is a way to load the code for more than one page on a single request.

As an example, let’s say I have multiple profile pages for a user (info, settings, history). I want to load the code for all of those pages on one request for any of those pages, so the navigation between them will be instant, and there will be no waiting time.

Advertisement

Answer

As long as the links (using next/link) to those pages are within the viewport the pages will be prefetched by default when in production mode (prefetch doesn’t work in dev mode, though).

prefetch – Prefetch the page in the background. Defaults to true. Any <Link /> that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing prefetch={false}. When prefetch is set to false, prefetching will still occur on hover. Pages using Static Generation will preload JSON files with the data for faster page transitions. Prefetching is only enabled in production.

If you’re not using next/link to navigate to those pages, then you can use router.prefetch to force the prefetch.

router.prefetch(url, as)

  • url – The URL to prefetch, including explicit routes (e.g. /dashboard) and dynamic routes (e.g. /product/[id])
  • as – Optional decorator for url. Before Next.js 9.5.3 this was used to prefetch dynamic routes, check our previous docs to see how it worked
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement