Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions packages/next/src/client/components/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<IntersectionObserverEntry>) {
// Process the entries in reverse order. The prefetch scheduler assigns the
// highest priority to the most recently scheduled task, so whichever link we
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions test/e2e/app-dir/link-download-prefetch/app/export/route.ts
Original file line number Diff line number Diff line change
@@ -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',
},
})
}
9 changes: 9 additions & 0 deletions test/e2e/app-dir/link-download-prefetch/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { ReactNode } from 'react'

export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
27 changes: 27 additions & 0 deletions test/e2e/app-dir/link-download-prefetch/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { LinkAccordion } from '../components/link-accordion'

export default function Page() {
return (
<main id="home-page">
<ul>
<li>
<LinkAccordion href="/target">Target page</LinkAccordion>
</li>
<li>
<LinkAccordion href="/export?variant=auto" download="report.csv">
Download CSV
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/export?variant=full"
download="report.csv"
prefetch={true}
>
Download CSV (prefetch=true)
</LinkAccordion>
</li>
</ul>
</main>
)
}
3 changes: 3 additions & 0 deletions test/e2e/app-dir/link-download-prefetch/app/target/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p id="target-page">Target page content</p>
}
Original file line number Diff line number Diff line change
@@ -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 (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch} download={download}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
Original file line number Diff line number Diff line change
@@ -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<typeof createRouterAct>
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('/')
})
})
6 changes: 6 additions & 0 deletions test/e2e/app-dir/link-download-prefetch/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}

module.exports = nextConfig
Loading