Unverified Commit 35f60806 authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Re-enable legacyBehavior and passHref on Link (#84500)

In https://github.com/vercel/next.js/pull/83003, `legacyBehavior` and
`passHref` were removed from `<Link>`. However, this turned out to be a
bit premature—despite most usage being covered by the newer `<Link>`
APIs, there's some use cases we don't yet have good alternatives for.

We expect to solve this with an API that uses Fragment Refs once they're
available in React. For now, we're re-enabling these flags.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 41e39426
...@@ -983,6 +983,7 @@ async fn apply_vendored_react_aliases_server( ...@@ -983,6 +983,7 @@ async fn apply_vendored_react_aliases_server(
// This is used in the server runtime to import React Server Components. // This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! { alias.extend(fxindexmap! {
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"), rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
}); });
} }
...@@ -1012,6 +1013,7 @@ async fn rsc_aliases( ...@@ -1012,6 +1013,7 @@ async fn rsc_aliases(
// This is used in the server runtime to import React Server Components. // This is used in the server runtime to import React Server Components.
alias.extend(fxindexmap! { alias.extend(fxindexmap! {
rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"), rcstr!("next/navigation") => rcstr!("next/dist/api/navigation.react-server"),
rcstr!("next/link") => rcstr!("next/dist/client/app-dir/link.react-server"),
}); });
} }
......
...@@ -860,5 +860,6 @@ ...@@ -860,5 +860,6 @@
"859": "An IO error occurred while attempting to create and acquire the lockfile", "859": "An IO error occurred while attempting to create and acquire the lockfile",
"860": "Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., \"5mb\")", "860": "Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., \"5mb\")",
"861": "Client Max Body Size must be larger than 0 bytes", "861": "Client Max Body Size must be larger than 0 bytes",
"862": "Request body exceeded %s" "862": "Request body exceeded %s",
"863": "\\`<Link legacyBehavior>\\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \\`<a>\\` tag."
} }
...@@ -238,6 +238,7 @@ export function createAppRouterApiAliases(isServerOnlyLayer: boolean) { ...@@ -238,6 +238,7 @@ export function createAppRouterApiAliases(isServerOnlyLayer: boolean) {
if (isServerOnlyLayer) { if (isServerOnlyLayer) {
mapping['navigation'] = 'next/dist/api/navigation.react-server' mapping['navigation'] = 'next/dist/api/navigation.react-server'
mapping['link'] = 'next/dist/client/app-dir/link.react-server'
} }
const aliasMap: Record<string, string> = {} const aliasMap: Record<string, string> = {}
......
import type { ComponentProps } from 'react'
import ClientLinkComponent, { type LinkProps, useLinkStatus } from './link'
export default function LinkComponent(
props: ComponentProps<typeof ClientLinkComponent>
) {
const isLegacyBehavior = props.legacyBehavior
const childIsHostComponent =
typeof props.children === 'string' ||
typeof props.children === 'number' ||
typeof (props.children as any)?.type === 'string'
const childIsClientComponent =
(props.children as any)?.type?.$$typeof ===
Symbol.for('react.client.reference')
if (isLegacyBehavior && !childIsHostComponent && !childIsClientComponent) {
if ((props.children as any)?.type?.$$typeof === Symbol.for('react.lazy')) {
console.error(
`Using a Lazy Component as a direct child of \`<Link legacyBehavior>\` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's \`<a>\` tag.`
)
} else {
console.error(
`Using a Server Component as a direct child of \`<Link legacyBehavior>\` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's \`<a>\` tag.`
)
}
}
return <ClientLinkComponent {...props} />
}
export { type LinkProps, useLinkStatus }
This diff is collapsed.
...@@ -17,7 +17,9 @@ import { startTransition } from 'react' ...@@ -17,7 +17,9 @@ import { startTransition } from 'react'
import { PrefetchKind } from './router-reducer/router-reducer-types' import { PrefetchKind } from './router-reducer/router-reducer-types'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
type Element = HTMLAnchorElement | HTMLFormElement type LinkElement = HTMLAnchorElement | SVGAElement
type Element = LinkElement | HTMLFormElement
// Properties that are shared between Link and Form instances. We use the same // Properties that are shared between Link and Form instances. We use the same
// shape for both to prevent a polymorphic de-opt in the VM. // shape for both to prevent a polymorphic de-opt in the VM.
...@@ -145,7 +147,7 @@ function coercePrefetchableUrl(href: string): URL | null { ...@@ -145,7 +147,7 @@ function coercePrefetchableUrl(href: string): URL | null {
} }
export function mountLinkInstance( export function mountLinkInstance(
element: HTMLAnchorElement, element: LinkElement,
href: string, href: string,
router: AppRouterInstance, router: AppRouterInstance,
fetchStrategy: PrefetchTaskFetchStrategy, fetchStrategy: PrefetchTaskFetchStrategy,
...@@ -255,7 +257,7 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) { ...@@ -255,7 +257,7 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) {
} }
export function onNavigationIntent( export function onNavigationIntent(
element: HTMLAnchorElement, element: HTMLAnchorElement | SVGAElement,
unstable_upgradeToDynamicPrefetch: boolean unstable_upgradeToDynamicPrefetch: boolean
) { ) {
const instance = prefetchable.get(element) const instance = prefetchable.get(element)
......
This diff is collapsed.
import { nextTestSetup } from 'e2e-utils'
describe('Link with legacyBehavior', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
describe('if the child is an <a> tag', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('#about-page').text()
expect(title).toBe('About Page')
})
})
it('works if the child is a number', async () => {
const browser = await next.browser('/child-is-a-number')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('works if the child is a string', async () => {
const browser = await next.browser('/child-is-a-string')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('errors when calling onClick without the event', async () => {
const browser = await next.browser('/invalid-onclick')
expect(await browser.elementByCss('#errors').text()).toBe('0')
await browser.elementByCss('#custom-button').click()
expect(await browser.elementByCss('#errors').text()).toBe('1')
})
it('should show a deprecation warning', async () => {
const browser = await next.browser('/')
const logs = await browser.log()
const errors = logs.filter(
(log) =>
log.source === 'error' &&
log.message.includes(
'`legacyBehavior` is deprecated and will be removed in a future release.'
)
)
console.log(errors)
expect(errors.length).toBe(isNextDev ? 1 : 0)
})
describe('passHref', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/passHref')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/passHref')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
})
})
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="about-page">About Page</h1>
<Link href="/" legacyBehavior>
<a>Home</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
{1000}
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Home Page</h1>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
import Link from 'next/link'
import { useState } from 'react'
export default function Page(props: any) {
const [errorCount, setErrorCount] = useState(0)
function Button(props) {
return (
<a
id="custom-button"
href={props.href}
onClick={(e) => {
e.preventDefault()
try {
props.onClick()
} catch (err) {
setErrorCount(errorCount + 1)
console.error(err)
}
}}
>
{props.href}
</a>
)
}
return (
<>
<p id="errors">{errorCount}</p>
<Link href="/nav" passHref legacyBehavior>
<Button />
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<CustomComponent>About</CustomComponent>
</Link>
</>
)
}
function CustomComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1 id="about-page">About Page</h1>
<Link href="/" legacyBehavior>
<a>Home</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
{1000}
</Link>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
About
</Link>
</>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export default function Page(props: any) {
const [errorCount, setErrorCount] = useState(0)
function Button(props) {
return (
<a
id="custom-button"
href={props.href}
onClick={(e) => {
e.preventDefault()
try {
props.onClick()
} catch (err) {
setErrorCount(errorCount + 1)
console.error(err)
}
}}
>
{props.href}
</a>
)
}
return (
<>
<p id="errors">{errorCount}</p>
<Link href="/nav" passHref legacyBehavior>
<Button />
</Link>
</>
)
}
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default async function Root({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<Suspense>
<Connection>
<body>{children}</body>
</Connection>
</Suspense>
</html>
)
}
async function Connection({ children }: { children: ReactNode }) {
await connection()
return children
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Home Page</h1>
<Link href="/about" legacyBehavior>
<a>About</a>
</Link>
</>
)
}
'use client'
export default function CustomComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import CustomComponent from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<CustomComponent>About</CustomComponent>
</Link>
</>
)
}
'use client'
import Link from 'next/link'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ChildComponent>About</ChildComponent>
</Link>
</>
)
}
function ChildComponent(props: any) {
return <a {...props} />
}
'use client'
import Link from 'next/link'
import { lazy } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
{/* @ts-ignore */}
{lazyJSX}
</Link>
</>
)
}
// @ts-ignore
const lazyJSX = lazy(() => Promise.resolve({ default: <a>About</a> }))
'use client'
import Link from 'next/link'
export default function Page() {
return <Link href="/about" legacyBehavior></Link>
}
'use client'
import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" legacyBehavior>
<span>a</span>
<span>b</span>
</Link>
)
}
import { ReactNode } from 'react'
import { ClientLink } from '../client-link'
export default function Page() {
return (
<>
<ClientLink href="/about">
<RSC>About</RSC>
</ClientLink>
</>
)
}
async function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
'use client'
import Link from 'next/link'
import { ComponentProps } from 'react'
export function ClientLink(props: ComponentProps<typeof Link>) {
return <Link legacyBehavior passHref {...props} />
}
'use client'
import { ReactNode } from 'react'
export default function ClientA({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { ClientLink } from '../client-link'
import ClientA from './_client'
export default function Page() {
return (
<>
<ClientLink href="/about">
<ClientA>
<RSC />
</ClientA>
</ClientLink>
</>
)
}
async function RSC() {
return <span>About</span>
}
'use client'
import { ReactNode } from 'react'
export default function ClientA({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { ClientLink } from '../client-link'
import ClientA from './_client'
export default function Page() {
return (
<>
<ClientLink href="/about">
<ClientA>About</ClientA>
</ClientLink>
</>
)
}
import { ReactNode } from 'react'
import { ClientLink } from '../client-link'
export default function Page() {
return (
<>
<ClientLink href="/about">
<RSC>About</RSC>
</ClientLink>
</>
)
}
function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
<RSC>About</RSC>
</Link>
</>
)
}
async function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
'use client'
export function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { ClientComponent } from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ClientComponent>
<RSC />
</ClientComponent>
</Link>
</>
)
}
function RSC() {
return <span>About</span>
}
'use client'
export function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { ClientComponent } from './_client'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<ClientComponent>About</ClientComponent>
</Link>
</>
)
}
'use client'
export default function ClientComponent(props: any) {
return <a {...props} />
}
import Link from 'next/link'
import { lazy } from 'react'
const LazyComponent = lazy(() => import('./_client'))
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior passHref>
<LazyComponent>About</LazyComponent>
</Link>
</>
)
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Page() {
return (
<>
<Link href="/about" legacyBehavior>
<RSC>About</RSC>
</Link>
</>
)
}
function RSC({ children }: { children: ReactNode }) {
return <a>{children}</a>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('Link with legacyBehavior', () => {
if (process.env.__NEXT_EXPERIMENTAL_DEBUG_CHANNEL) {
it('should skip debug mode test', () => {})
return
}
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return it('should skip', () => {})
}
describe('if the child is an <a> tag', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('#about-page').text()
expect(title).toBe('About Page')
})
})
it('works if the child is a number', async () => {
const browser = await next.browser('/child-is-a-number')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('works if the child is a string', async () => {
const browser = await next.browser('/child-is-a-string')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
it('errors when calling onClick without the event', async () => {
const browser = await next.browser('/invalid-onclick')
expect(await browser.elementByCss('#errors').text()).toBe('0')
await browser.elementByCss('#custom-button').click()
expect(await browser.elementByCss('#errors').text()).toBe('1')
})
it('should show a deprecation warning', async () => {
const browser = await next.browser('/')
await retry(async () => {
const logs = await browser.log()
const errors = logs.filter((log) => log.source === 'error')
if (isNextDev) {
expect(errors).toEqual([
{
message:
'`legacyBehavior` is deprecated and will be removed in a future release. A codemod is available to upgrade your components:\n\n' +
'npx @next/codemod@latest new-link .\n\n' +
'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components',
source: 'error',
},
])
} else {
expect(errors).toEqual([])
}
})
})
describe('passHref', () => {
it('forwards the href attribute', async () => {
const $ = await next.render$('/passHref')
const $a = $('a')
expect($a.text()).toBe('About')
expect($a.attr('href')).toBe('/about')
})
it('navigates correctly', async () => {
const browser = await next.browser('/passHref')
await browser.elementByCss('a').click()
const title = await browser.elementByCss('h1').text()
expect(title).toBe('About Page')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
cacheComponents: true,
},
}
module.exports = nextConfig
This diff is collapsed.
...@@ -27,11 +27,11 @@ describe('New Link Behavior with <a> child', () => { ...@@ -27,11 +27,11 @@ describe('New Link Behavior with <a> child', () => {
if (isNextDev) { if (isNextDev) {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
'Error: Invalid <Link> with <a> child. Please remove <a>' 'Error: Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>'
) )
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Invalid <Link> with <a> child. Please remove <a>. "description": "Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.
Learn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor", Learn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor",
"environmentLabel": null, "environmentLabel": null,
"label": "Runtime Error", "label": "Runtime Error",
......
...@@ -3,15 +3,9 @@ import { textValue, TestLink } from './lib/shared-module' ...@@ -3,15 +3,9 @@ import { textValue, TestLink } from './lib/shared-module'
export function middleware(request) { export function middleware(request) {
if (request.nextUrl.pathname === '/middleware') { if (request.nextUrl.pathname === '/middleware') {
let testLink
try {
testLink = TestLink.$$typeof.toString()
} catch (e) {
testLink = e.message
}
return Response.json({ return Response.json({
clientReference: testLink,
textValue, textValue,
linkType: typeof TestLink,
}) })
} }
......
...@@ -10,7 +10,7 @@ describe('rsc layers transform', () => { ...@@ -10,7 +10,7 @@ describe('rsc layers transform', () => {
expect(json).toEqual({ expect(json).toEqual({
textValue: 'text-value', textValue: 'text-value',
clientReference: 'Symbol(react.client.reference)', linkType: 'function',
}) })
}) })
......
import * as React from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
<h1>Navigation worked!</h1>
<Link href="/">Go back</Link>
</>
)
}
/** @type {import('next').NextConfig} */
export default {}
'use client'
import Link from 'next/link'
import {
useCallback,
useState,
type ComponentPropsWithRef,
type ReactNode,
type Ref,
type RefCallback,
} from 'react'
export default function Page() {
return (
<>
<h1>Home</h1>
<ToggleVisibility>
<Link href="/link-target" legacyBehavior>
<AnchorThatDoesRefMerging id="test-link">
Go to /link-target
</AnchorThatDoesRefMerging>
</Link>
</ToggleVisibility>
</>
)
}
function ToggleVisibility({ children }: { children: ReactNode }) {
const [isVisible, setIsVisible] = useState(true)
return (
<>
<div>
<button type="button" onClick={() => setIsVisible((prev) => !prev)}>
{isVisible ? 'Hide content' : 'Show content'}
</button>
</div>
{isVisible ? children : null}
</>
)
}
function AnchorThatDoesRefMerging({
ref,
children,
...anchorProps
}: ComponentPropsWithRef<'a'>) {
const customRef: RefCallback<HTMLAnchorElement> = useCallback((el) => {
if (el) {
console.log('hello friends i am here')
} else {
console.log('goodbye friends i am gone')
}
}, [])
const finalRef = useBuggyRefMerge(customRef, ref ?? null)
return (
<a ref={finalRef} {...anchorProps}>
{children}
</a>
)
}
/** A ref-merging function that doesn't account for cleanup refs (added in React 19)
* https://react.dev/blog/2024/12/05/react-19#cleanup-functions-for-refs
*/
function useBuggyRefMerge<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): RefCallback<TElement> {
return useCallback(
(current: TElement | null) => {
for (const ref of [refA, refB]) {
if (!ref) {
continue
}
if (typeof ref === 'object') {
ref.current = current
} else {
// BUG!!!
// This would work in 18, but in 19 it can return a cleanup which will get swallowed here
ref(current)
}
}
},
[refA, refB]
)
}
import { nextTestSetup } from 'e2e-utils'
// NOTE: this test is checking for a bug in prefetching code,
// so we only enable it in production
describe('Link with legacyBehavior - handles buggy userspace ref merging', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('does not crash when Link unmounts', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('h1').text()).toEqual('Home')
expect(await browser.hasElementByCssSelector('#test-link')).toBe(true)
// hide the link, unmounting it
await browser.elementByCss('button').click()
expect(await browser.hasElementByCssSelector('#test-link')).toBe(false)
// shouldn't cause a crash
expect(await browser.elementByCss('h1').text()).toEqual('Home')
expect(await browser.elementByCss('body').text()).not.toContain(
'Application error: a client-side exception has occurred'
)
})
})
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