Unverified Commit fdd7f762 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Reland "[Link] Add prefetch="auto" option" (#78821)

Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent 7e4b3376
......@@ -133,7 +133,7 @@ type InternalLinkProps = {
* Prefetching is only enabled in production.
*
* - In the **App Router**:
* - `null` (default): Prefetch behavior depends on static vs dynamic routes:
* - `"auto"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes:
* - Static routes: fully prefetched
* - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`
* - `true`: Always prefetch the full route and data.
......@@ -151,7 +151,7 @@ type InternalLinkProps = {
* </Link>
* ```
*/
prefetch?: boolean | null
prefetch?: boolean | 'auto' | null
/**
* (unstable) Switch to a dynamic prefetch on hover. Effectively the same as
......@@ -366,7 +366,9 @@ export default function LinkComponent(
* - 'unstable_dynamicOnHover': this starts in "auto" mode, but switches to "full" when the link is hovered
*/
const appPrefetchKind =
prefetchProp === null ? PrefetchKind.AUTO : PrefetchKind.FULL
prefetchProp === null || prefetchProp === 'auto'
? PrefetchKind.AUTO
: PrefetchKind.FULL
if (process.env.NODE_ENV !== 'production') {
function createPropError(args: {
......@@ -455,7 +457,6 @@ export default function LinkComponent(
key === 'scroll' ||
key === 'shallow' ||
key === 'passHref' ||
key === 'prefetch' ||
key === 'legacyBehavior' ||
key === 'unstable_dynamicOnHover'
) {
......@@ -466,6 +467,18 @@ export default function LinkComponent(
actual: valType,
})
}
} else if (key === 'prefetch') {
if (
props[key] != null &&
valType !== 'boolean' &&
props[key] !== 'auto'
) {
throw createPropError({
key,
expected: '`boolean | "auto"`',
actual: valType,
})
}
} else {
// TypeScript trick for type-guarding:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
......
......@@ -19,7 +19,7 @@ type InternalFormProps = {
* Prefetch can be disabled by passing `prefetch={false}`. Prefetching is only enabled in production.
*
* Options:
* - `null` (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - "auto", null, undefined (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - `false`: This will not prefetch any data.
*
* In pages dir, prefetching is not supported, and passing this prop will emit a warning.
......
......@@ -73,7 +73,7 @@ type InternalLinkProps = {
* Prefetch can be disabled by passing `prefetch={false}`. Prefetching is only enabled in production.
*
* In App Router:
* - `null` (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - "auto", null, undefined (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - `true`: This will prefetch the full React Server Component data for all route segments, regardless of whether they contain a segment with `loading.js`.
* - `false`: This will not prefetch any data, even on hover.
*
......@@ -82,7 +82,7 @@ type InternalLinkProps = {
* - `false`: Prefetching will not happen when entering the viewport, but will still happen on hover.
* @defaultValue `true` (pages router) or `null` (app router)
*/
prefetch?: boolean | null
prefetch?: boolean | 'auto' | null
/**
* The active locale is automatically prepended. `locale` allows for providing a different locale.
* When `false` `href` has to include the locale as the default behavior is disabled.
......@@ -419,7 +419,6 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
key === 'scroll' ||
key === 'shallow' ||
key === 'passHref' ||
key === 'prefetch' ||
key === 'legacyBehavior'
) {
if (props[key] != null && valType !== 'boolean') {
......@@ -429,6 +428,18 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
actual: valType,
})
}
} else if (key === 'prefetch') {
if (
props[key] != null &&
valType !== 'boolean' &&
props[key] !== 'auto'
) {
throw createPropError({
key,
expected: '`boolean | "auto"`',
actual: valType,
})
}
} else {
// TypeScript trick for type-guarding:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
......
export default function Loading() {
return <div id="loading-boundary">Loading...</div>
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return <div id="dynamic-content">Dynamic content</div>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<>
<p>
This page is used to test that prefetch="auto" uses the default
prefetching strategy (the same as if no prefetch prop is given).
</p>
<LinkAccordion prefetch="auto" href="/dynamic">
Dynamic page with loading boundary
</LinkAccordion>
</>
)
}
'use client'
import Link, { LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: LinkProps['href']
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
// This component is used to test the prefetching strategy of the Link component
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
dynamicIO: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('<Link prefetch="auto">', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (isNextDev || skipped) {
it('disabled in development / deployment', () => {})
return
}
// NOTE: Since "auto" is just an alias for the default, I'm not bothering to
// write tests for every default prefetching behavior; that's covered by a
// bunch of other test suites. This is just a quick test to confirm that the
// alias exists.
it('<Link prefetch="auto"> works the same as if prefetch were undefined or null', async () => {
// Test that the link only prefetches the static part of the target page
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Reveal the link to trigger a prefetch
await act(async () => {
const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/dynamic"]'
)
await linkToggle.click()
}, [
// Should prefetch the loading boundary
{
includes: 'Loading...',
},
// Should not prefetch the dynamic content
{
includes: 'Dynamic content',
block: 'reject',
},
])
// Navigate to the page
await act(
async () => {
await browser.elementByCss('a[href="/dynamic"]').click()
},
{
// Now the dynamic content should be fetched
includes: 'Dynamic content',
}
)
})
})
import Link from 'next/link'
export const dynamic = 'force-dynamic'
export default function Hello() {
return (
<Link prefetch="unknown" href="https://nextjs.org/">
Link with unknown `prefetch` renders in prod.
</Link>
)
}
......@@ -83,4 +83,34 @@ describe('next-link', () => {
`"Application error: a client-side exception has occurred while loading localhost (see the browser console for more information)."`
)
})
it('invalid `prefetch` causes runtime error (dev-only)', async () => {
const browser = await webdriver(next.appPort, '/invalid-prefetch')
if (isNextDev) {
// TODO(veil): https://linear.app/vercel/issue/NDX-554/hide-the-anonymous-frames-which-are-between-2-ignored-frames
await expect(browser).toDisplayRedbox(`
{
"description": "Failed prop type: The prop \`prefetch\` expects a \`boolean | "auto"\` in \`<Link>\`, but got \`string\` instead.
Open your browser's console to view the Component stack trace.",
"environmentLabel": null,
"label": "Runtime Error",
"source": "app/invalid-prefetch/page.js (7:5) @ Hello
> 7 | <Link prefetch="unknown" href="https://nextjs.org/">
| ^",
"stack": [
"Array.forEach <anonymous> (0:0)",
"Hello app/invalid-prefetch/page.js (7:5)",
],
}
`)
expect(await browser.elementByCss('body').text()).toMatchInlineSnapshot(
`"Application error: a client-side exception has occurred while loading localhost (see the browser console for more information)."`
)
} else {
expect(await browser.elementByCss('body').text()).toMatchInlineSnapshot(
`"Link with unknown \`prefetch\` renders in prod."`
)
}
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment