From 8a4a012ac5c757f916e303baeba1ae90da4e8389 Mon Sep 17 00:00:00 2001 From: Joseph Date: Wed, 25 Nov 2026 23:49:38 +0100 Subject: [PATCH 1/2] Skip prefetching for Link with a download attribute A click on is already left to the browser, so it never becomes a client-side navigation. Prefetching it still requested the target with RSC headers, which runs a Route Handler (for example a CSV export) before the user clicks. Skip registering these links for viewport and hover prefetching. Co-authored-by: vercel-v[bot] <353008837+vercel-v[bot]@users.noreply.github.com> --- packages/next/src/client/app-dir/link.tsx | 17 +++- .../app/export/route.ts | 8 ++ .../link-download-prefetch/app/layout.tsx | 9 ++ .../link-download-prefetch/app/page.tsx | 27 ++++++ .../app/target/page.tsx | 3 + .../components/link-accordion.tsx | 35 ++++++++ .../link-download-prefetch.test.ts | 88 +++++++++++++++++++ .../link-download-prefetch/next.config.js | 6 ++ 8 files changed, 192 insertions(+), 1 deletion(-) create mode 100644 test/e2e/app-dir/link-download-prefetch/app/export/route.ts create mode 100644 test/e2e/app-dir/link-download-prefetch/app/layout.tsx create mode 100644 test/e2e/app-dir/link-download-prefetch/app/page.tsx create mode 100644 test/e2e/app-dir/link-download-prefetch/app/target/page.tsx create mode 100644 test/e2e/app-dir/link-download-prefetch/components/link-accordion.tsx create mode 100644 test/e2e/app-dir/link-download-prefetch/link-download-prefetch.test.ts create mode 100644 test/e2e/app-dir/link-download-prefetch/next.config.js diff --git a/packages/next/src/client/app-dir/link.tsx b/packages/next/src/client/app-dir/link.tsx index ad772ce70b45..67f862c52015 100644 --- a/packages/next/src/client/app-dir/link.tsx +++ b/packages/next/src/client/app-dir/link.tsx @@ -634,6 +634,13 @@ export default function LinkComponent( }, [prefetchStage]) : undefined + // With `legacyBehavior`, `download` is set on the child instead of ``. + // React omits the attribute when the value is `false`, `null`, or `undefined`. + const download: unknown = legacyBehavior + ? child?.props?.download + : (restProps as React.AnchorHTMLAttributes).download + const hasDownloadProp = download != null && download !== false + // Use a callback ref to attach an IntersectionObserver to the anchor tag on // mount. In the future we will also use this to keep track of all the // currently mounted instances, e.g. so we can re-prefetch them after @@ -646,7 +653,14 @@ export default function LinkComponent( formattedHref, router, prefetchStage, - prefetchEnabled, + // A click on a link with a `download` attribute is left to the + // browser (see `linkClicked`), so it never becomes a client-side + // navigation and there is nothing to prefetch. Its target is usually + // a Route Handler, which a prefetch request would run. The element + // check also covers a custom `legacyBehavior` child that sets it. + prefetchEnabled && + !hasDownloadProp && + !element.hasAttribute('download'), setOptimisticLinkStatus, ownerStack ) @@ -667,6 +681,7 @@ export default function LinkComponent( prefetchStage, setOptimisticLinkStatus, ownerStack, + hasDownloadProp, ] ) diff --git a/test/e2e/app-dir/link-download-prefetch/app/export/route.ts b/test/e2e/app-dir/link-download-prefetch/app/export/route.ts new file mode 100644 index 000000000000..5598ddf8ed17 --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/app/export/route.ts @@ -0,0 +1,8 @@ +export async function GET() { + return new Response('id,name\n1,Next.js\n', { + headers: { + 'Content-Type': 'text/csv', + 'Content-Disposition': 'attachment', + }, + }) +} diff --git a/test/e2e/app-dir/link-download-prefetch/app/layout.tsx b/test/e2e/app-dir/link-download-prefetch/app/layout.tsx new file mode 100644 index 000000000000..7c3f422f0039 --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/app/layout.tsx @@ -0,0 +1,9 @@ +import type { ReactNode } from 'react' + +export default function Root({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} diff --git a/test/e2e/app-dir/link-download-prefetch/app/page.tsx b/test/e2e/app-dir/link-download-prefetch/app/page.tsx new file mode 100644 index 000000000000..1b473dad20c7 --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/app/page.tsx @@ -0,0 +1,27 @@ +import { LinkAccordion } from '../components/link-accordion' + +export default function Page() { + return ( +
+
    +
  • + Target page +
  • +
  • + + Download CSV + +
  • +
  • + + Download CSV (prefetch=true) + +
  • +
+
+ ) +} diff --git a/test/e2e/app-dir/link-download-prefetch/app/target/page.tsx b/test/e2e/app-dir/link-download-prefetch/app/target/page.tsx new file mode 100644 index 000000000000..3e2612aa98c7 --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/app/target/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

Target page content

+} diff --git a/test/e2e/app-dir/link-download-prefetch/components/link-accordion.tsx b/test/e2e/app-dir/link-download-prefetch/components/link-accordion.tsx new file mode 100644 index 000000000000..8f5f0c08ab5b --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/components/link-accordion.tsx @@ -0,0 +1,35 @@ +'use client' + +import Link, { type LinkProps } from 'next/link' +import { useState } from 'react' + +export function LinkAccordion({ + href, + children, + prefetch, + download, +}: { + href: string + children: React.ReactNode + prefetch?: LinkProps['prefetch'] + download?: string | boolean +}) { + const [isVisible, setIsVisible] = useState(false) + return ( + <> + setIsVisible(!isVisible)} + data-link-accordion={href} + /> + {isVisible ? ( + + {children} + + ) : ( + <>{children} (link is hidden) + )} + + ) +} diff --git a/test/e2e/app-dir/link-download-prefetch/link-download-prefetch.test.ts b/test/e2e/app-dir/link-download-prefetch/link-download-prefetch.test.ts new file mode 100644 index 000000000000..c3a79ed88da3 --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/link-download-prefetch.test.ts @@ -0,0 +1,88 @@ +import { nextTestSetup } from 'e2e-utils' +import type * as Playwright from 'playwright' +import { createRouterAct } from 'router-act' + +describe('link-download-prefetch', () => { + const { next, isNextDev } = nextTestSetup({ + files: __dirname, + }) + + if (isNextDev) { + test('prefetching is disabled', () => {}) + return + } + + // App Shell prefetches are ignored by `act` by default. Include them so + // 'no-requests' fails on any request that would reach the Route Handler. + async function openHomePage() { + let act: ReturnType + let page: Playwright.Page + const browser = await next.browser('/', { + beforePageLoad(p: Playwright.Page) { + page = p + act = createRouterAct(p, { includeAppShellRequests: true }) + }, + }) + return { browser, act: act!, page: page! } + } + + it('prefetches a regular Link', async () => { + const { browser, act } = await openHomePage() + + await act( + async () => { + await browser + .elementByCss('input[data-link-accordion="/target"]') + .click() + await browser.elementByCss('a[href="/target"]') + }, + { includes: 'Target page content' } + ) + }) + + it.each([ + ['the default prefetch', '/export?variant=auto'], + ['prefetch={true}', '/export?variant=full'], + ])( + 'does not prefetch a Link with a download attribute and %s', + async (_, href) => { + const { browser, act } = await openHomePage() + + // Reveal the link. It enters the viewport, which would normally schedule + // a prefetch that runs the Route Handler. + await act(async () => { + await browser + .elementByCss(`input[data-link-accordion="${href}"]`) + .click() + await browser.elementByCss(`a[href="${href}"]`) + }, 'no-requests') + + // Hovering would normally upgrade or re-trigger the prefetch. + const link = await browser.elementByCss(`a[href="${href}"]`) + await act(async () => { + await link.hover() + }, 'no-requests') + } + ) + + it('lets the browser download the file on click without a router request', async () => { + const { browser, act, page } = await openHomePage() + const href = '/export?variant=auto' + + await act(async () => { + await browser.elementByCss(`input[data-link-accordion="${href}"]`).click() + }, 'no-requests') + + const downloadPromise = page.waitForEvent('download') + await act(async () => { + await browser.elementByCss(`a[href="${href}"]`).click() + }, 'no-requests') + + const download = await downloadPromise + // The handler sends `Content-Disposition: attachment` without a filename, + // so the browser only uses the `download` attribute's filename when it + // handles the click itself instead of a client-side navigation. + expect(download.suggestedFilename()).toBe('report.csv') + expect(new URL(await browser.url()).pathname).toBe('/') + }) +}) diff --git a/test/e2e/app-dir/link-download-prefetch/next.config.js b/test/e2e/app-dir/link-download-prefetch/next.config.js new file mode 100644 index 000000000000..807126e4cf0b --- /dev/null +++ b/test/e2e/app-dir/link-download-prefetch/next.config.js @@ -0,0 +1,6 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = {} + +module.exports = nextConfig From 57b715cf8e417cb17916f8acd671802c82e35873 Mon Sep 17 00:00:00 2001 From: Joseph Chamochumbi Date: Thu, 26 Nov 2026 17:08:45 +0100 Subject: [PATCH 2/2] Check the download attribute when scheduling a Link prefetch --- packages/next/src/client/app-dir/link.tsx | 17 +---------------- packages/next/src/client/components/links.ts | 14 +++++++++++--- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/packages/next/src/client/app-dir/link.tsx b/packages/next/src/client/app-dir/link.tsx index 67f862c52015..ad772ce70b45 100644 --- a/packages/next/src/client/app-dir/link.tsx +++ b/packages/next/src/client/app-dir/link.tsx @@ -634,13 +634,6 @@ export default function LinkComponent( }, [prefetchStage]) : undefined - // With `legacyBehavior`, `download` is set on the child instead of ``. - // React omits the attribute when the value is `false`, `null`, or `undefined`. - const download: unknown = legacyBehavior - ? child?.props?.download - : (restProps as React.AnchorHTMLAttributes).download - const hasDownloadProp = download != null && download !== false - // Use a callback ref to attach an IntersectionObserver to the anchor tag on // mount. In the future we will also use this to keep track of all the // currently mounted instances, e.g. so we can re-prefetch them after @@ -653,14 +646,7 @@ export default function LinkComponent( formattedHref, router, prefetchStage, - // A click on a link with a `download` attribute is left to the - // browser (see `linkClicked`), so it never becomes a client-side - // navigation and there is nothing to prefetch. Its target is usually - // a Route Handler, which a prefetch request would run. The element - // check also covers a custom `legacyBehavior` child that sets it. - prefetchEnabled && - !hasDownloadProp && - !element.hasAttribute('download'), + prefetchEnabled, setOptimisticLinkStatus, ownerStack ) @@ -681,7 +667,6 @@ export default function LinkComponent( prefetchStage, setOptimisticLinkStatus, ownerStack, - hasDownloadProp, ] ) diff --git a/packages/next/src/client/components/links.ts b/packages/next/src/client/components/links.ts index 2ba076c459ac..7898c861294b 100644 --- a/packages/next/src/client/components/links.ts +++ b/packages/next/src/client/components/links.ts @@ -245,6 +245,14 @@ export function unmountPrefetchableInstance(element: Element) { } } +// A click on a link with a `download` attribute is left to the browser (see +// `linkClicked` in app-dir/link.tsx), so it never becomes a client-side +// navigation and there is nothing to prefetch. Its target is usually a Route +// Handler, which a prefetch request would run. +function isDownloadLink(element: Element): boolean { + return element.hasAttribute('download') +} + function handleIntersect(entries: Array) { // Process the entries in reverse order. The prefetch scheduler assigns the // highest priority to the most recently scheduled task, so whichever link we @@ -277,8 +285,8 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) { return } - instance.isVisible = isVisible - if (isVisible) { + instance.isVisible = isVisible && !isDownloadLink(element) + if (instance.isVisible) { prefetchableAndVisible.add(instance) } else { prefetchableAndVisible.delete(instance) @@ -291,7 +299,7 @@ export function onNavigationIntent( unstable_upgradeToDynamicPrefetch: boolean ) { const instance = prefetchable.get(element) - if (instance === undefined) { + if (instance === undefined || isDownloadLink(element)) { return } // Prefetch the link on hover/touchstart.