From cc9265439610309288a6641a09082b78ee0dd63c Mon Sep 17 00:00:00 2001 From: Zack Tanner <1939140+ztanner@users.noreply.github.com> Date: Wed, 7 Aug 2024 18:35:34 -0700 Subject: [PATCH] fix app router prefetch deduping (#68642) The `Link` component has built in prefetch deduping behavior that was added for pages router, since pages only supports a single kind of prefetch. Both pages & app routers share the `Link` component, meaning the deduping behavior was enabled for both. However, app router supports different [prefetch types](https://nextjs.org/docs/app/api-reference/components/link#prefetch). This means that if a page contains a link to a URL with auto prefetching, followed by a URL with `prefetch={true}`, the full prefetch would not be applied because it was short-circuited by `Link`. Closes NDX-124 --- packages/next/src/client/link.tsx | 7 ++-- .../app-prefetch/app/prefetch-race/page.js | 19 +++++++++++ .../app-dir/app-prefetch/prefetching.test.ts | 33 ++++++++++++++++++- 3 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 test/e2e/app-dir/app-prefetch/app/prefetch-race/page.js diff --git a/packages/next/src/client/link.tsx b/packages/next/src/client/link.tsx index d10cc2f6670b0..8063ddd07a14c 100644 --- a/packages/next/src/client/link.tsx +++ b/packages/next/src/client/link.tsx @@ -148,8 +148,11 @@ function prefetch( } // We should only dedupe requests when experimental.optimisticClientCache is - // disabled. - if (!options.bypassPrefetchedCheck) { + // disabled & when we're not using the app router. App router handles + // reusing an existing prefetch entry (if it exists) for the same URL. + // If we dedupe in here, we will cause a race where different prefetch kinds + // to the same URL (ie auto vs true) will cause one to be ignored. + if (!options.bypassPrefetchedCheck && !isAppRouter) { const locale = // Let the link's locale prop override the default router locale. typeof options.locale !== 'undefined' diff --git a/test/e2e/app-dir/app-prefetch/app/prefetch-race/page.js b/test/e2e/app-dir/app-prefetch/app/prefetch-race/page.js new file mode 100644 index 0000000000000..e01e7a2d0f9ea --- /dev/null +++ b/test/e2e/app-dir/app-prefetch/app/prefetch-race/page.js @@ -0,0 +1,19 @@ +import Link from 'next/link' +import React from 'react' + +export default function Page() { + return ( + <> +