#How do I make those instant page navigations like in demo commerce from vercel
1 messages · Page 1 of 1 (latest)
To achieve instant page navigations like in the Vercel Commerce demo, you primarily need to leverage Next.js's built-in prefetching and caching mechanisms. Here’s how it works and what you need to consider:
1. Use <Link> with Prefetching
Next.js automatically prefetches linked routes when a <Link /> component enters the viewport (in production). This means the code and data for the linked page are loaded in the background, so when a user clicks the link, navigation is nearly instant. Prefetching is enabled by default, but you can control it with the prefetch prop. For full prefetching, set prefetch={true} on your <Link /> components. This works for both static and dynamic routes in the App Router and Pages Router, but the behavior differs slightly between them (App Router prefetch docs, Pages Router prefetch docs).
2. Client-side Router Cache
Next.js maintains an in-memory client-side router cache. When a user navigates, the cache is reused, resulting in instant back/forward navigation and no full-page reloads. Layouts and loading states are cached and reused, while pages are reused during browser navigation. The cache is cleared on page refresh, and its duration depends on how the resource was prefetched and whether it was statically generated (Client-side Router Cache).
3. Both Pages Do Not Need to Be on the Server
You do not need both pages to be server-rendered. Instant navigation works with static, server-side, and incrementally static regenerated (ISR) pages. The key is that the page is prefetched and cached before navigation. For static and ISR pages, the HTML is generated at build time or on-demand and cached at the edge, which also contributes to fast navigation (Pagination with SSG example).
4. Programmatic Prefetching
You can also programmatically prefetch routes using router.prefetch() from the useRouter hook. This is useful for scenarios where you want to prefetch a route in response to a user action (e.g., after login) (router.prefetch docs).
5. Limitations and Hard Navigations
If you are navigating between the App Router and Pages Router (mixed routing), automatic prefetching with next/link does not work across routers, and you will experience a hard navigation (full page reload). You can optimize these hard navigations by using browser-level prefetching techniques like <link rel="prefetch" href="..."> or custom strategies (Optimizing hard navigations).
Summary:
- Use
<Link prefetch={true}>for automatic prefetching. - Next.js caches route segments and data for instant navigation.
- Both static and server-rendered pages can benefit from instant navigation.
- Use
router.prefetch()for programmatic prefetching. - For mixed routing (App/Pages Router), consider additional prefetching strategies.