Unverified Commit 8aebac17 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Development: Don't import app-router / hot-reloader through next/link in application code (#83656)

## What?

Removes imports from the app-ssr layer that cause transitive
dependencies to be included during compilation in development.

For the trace that I received from an application there was quite a bit
of overhead for them because of this issue.

Trace:

![CleanShot 2025-09-10 at
21.32.27@2x.png](https://app.graphite.dev/user-attachments/assets/8a7e5323-ed3c-4aec-8723-7fbbae89a99d.png)
parent a64c5915
...@@ -18,7 +18,6 @@ import { ...@@ -18,7 +18,6 @@ import {
type LinkInstance, type LinkInstance,
} from '../components/links' } from '../components/links'
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url' import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { dispatchNavigateAction } from '../components/app-router-instance'
import { import {
FetchStrategy, FetchStrategy,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
...@@ -221,47 +220,52 @@ function linkClicked( ...@@ -221,47 +220,52 @@ function linkClicked(
scroll?: boolean, scroll?: boolean,
onNavigate?: OnNavigateEventHandler onNavigate?: OnNavigateEventHandler
): void { ): void {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) { if (typeof window !== 'undefined') {
// ignore click for browser’s default behavior if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
return // ignore click for browser’s default behavior
} return
if (!isLocalURL(href)) {
if (replace) {
// browser default behavior does not replace the history state
// so we need to do it manually
e.preventDefault()
location.replace(href)
} }
// ignore click for browser’s default behavior if (!isLocalURL(href)) {
return if (replace) {
} // browser default behavior does not replace the history state
// so we need to do it manually
e.preventDefault()
location.replace(href)
}
e.preventDefault() // ignore click for browser’s default behavior
return
}
if (onNavigate) { e.preventDefault()
let isDefaultPrevented = false
onNavigate({ if (onNavigate) {
preventDefault: () => { let isDefaultPrevented = false
isDefaultPrevented = true
},
})
if (isDefaultPrevented) { onNavigate({
return preventDefault: () => {
isDefaultPrevented = true
},
})
if (isDefaultPrevented) {
return
}
} }
}
React.startTransition(() => { const { dispatchNavigateAction } =
dispatchNavigateAction( require('../components/app-router-instance') as typeof import('../components/app-router-instance')
as || href,
replace ? 'replace' : 'push', React.startTransition(() => {
scroll ?? true, dispatchNavigateAction(
linkInstanceRef.current as || href,
) replace ? 'replace' : 'push',
}) scroll ?? true,
linkInstanceRef.current
)
})
}
} }
function formatStringOrUrl(urlObjOrString: UrlObject | string): string { function formatStringOrUrl(urlObjOrString: UrlObject | string): string {
......
...@@ -21,7 +21,7 @@ import { ...@@ -21,7 +21,7 @@ import {
} from './segment-cache' } from './segment-cache'
import { dispatchAppRouterAction } from './use-action-queue' import { dispatchAppRouterAction } from './use-action-queue'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { createPrefetchURL, isExternalURL } from './app-router' import { createPrefetchURL, isExternalURL } from './app-router-utils'
import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer' import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer'
import type { import type {
AppRouterInstance, AppRouterInstance,
......
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path'
export function isExternalURL(url: URL) {
return url.origin !== window.location.origin
}
/**
* Given a link href, constructs the URL that should be prefetched. Returns null
* in cases where prefetching should be disabled, like external URLs, or
* during development.
* @param href The href passed to <Link>, router.prefetch(), or similar
* @returns A URL object to prefetch, or null if prefetching should be disabled
*/
export function createPrefetchURL(href: string): URL | null {
// Don't prefetch for bots as they don't navigate.
if (isBot(window.navigator.userAgent)) {
return null
}
let url: URL
try {
url = new URL(addBasePath(href), window.location.href)
} catch (_) {
// TODO: Does this need to throw or can we just console.error instead? Does
// anyone rely on this throwing? (Seems unlikely.)
throw new Error(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
}
// Don't prefetch during development (improves compilation performance)
if (process.env.NODE_ENV === 'development') {
return null
}
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return null
}
return url
}
'use client'
import React, { import React, {
useEffect, useEffect,
useMemo, useMemo,
...@@ -25,8 +23,6 @@ import { ...@@ -25,8 +23,6 @@ import {
PathParamsContext, PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' import { dispatchAppRouterAction, useActionQueue } from './use-action-queue'
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
...@@ -53,47 +49,6 @@ const globalMutable: { ...@@ -53,47 +49,6 @@ const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
} = {} } = {}
export function isExternalURL(url: URL) {
return url.origin !== window.location.origin
}
/**
* Given a link href, constructs the URL that should be prefetched. Returns null
* in cases where prefetching should be disabled, like external URLs, or
* during development.
* @param href The href passed to <Link>, router.prefetch(), or similar
* @returns A URL object to prefetch, or null if prefetching should be disabled
*/
export function createPrefetchURL(href: string): URL | null {
// Don't prefetch for bots as they don't navigate.
if (isBot(window.navigator.userAgent)) {
return null
}
let url: URL
try {
url = new URL(addBasePath(href), window.location.href)
} catch (_) {
// TODO: Does this need to throw or can we just console.error instead? Does
// anyone rely on this throwing? (Seems unlikely.)
throw new Error(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
}
// Don't prefetch during development (improves compilation performance)
if (process.env.NODE_ENV === 'development') {
return null
}
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return null
}
return url
}
function HistoryUpdater({ function HistoryUpdater({
appRouterState, appRouterState,
}: { }: {
......
import type { FlightRouterState } from '../../shared/lib/app-router-types' import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { getCurrentAppRouterState } from './app-router-instance'
import { createPrefetchURL } from './app-router'
import { import {
FetchStrategy, FetchStrategy,
isPrefetchTaskDirty, isPrefetchTaskDirty,
...@@ -122,19 +120,26 @@ function observeVisibility(element: Element, instance: PrefetchableInstance) { ...@@ -122,19 +120,26 @@ function observeVisibility(element: Element, instance: PrefetchableInstance) {
} }
function coercePrefetchableUrl(href: string): URL | null { function coercePrefetchableUrl(href: string): URL | null {
try { if (typeof window !== 'undefined') {
return createPrefetchURL(href) const { createPrefetchURL } =
} catch { require('./app-router-utils') as typeof import('./app-router-utils')
// createPrefetchURL sometimes throws an error if an invalid URL is
// provided, though I'm not sure if it's actually necessary. try {
// TODO: Consider removing the throw from the inner function, or change it return createPrefetchURL(href)
// to reportError. Or maybe the error isn't even necessary for automatic } catch {
// prefetches, just navigations. // createPrefetchURL sometimes throws an error if an invalid URL is
const reportErrorFn = // provided, though I'm not sure if it's actually necessary.
typeof reportError === 'function' ? reportError : console.error // TODO: Consider removing the throw from the inner function, or change it
reportErrorFn( // to reportError. Or maybe the error isn't even necessary for automatic
`Cannot prefetch '${href}' because it cannot be converted to a URL.` // prefetches, just navigations.
) const reportErrorFn =
typeof reportError === 'function' ? reportError : console.error
reportErrorFn(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
return null
}
} else {
return null return null
} }
} }
...@@ -274,51 +279,57 @@ function rescheduleLinkPrefetch( ...@@ -274,51 +279,57 @@ function rescheduleLinkPrefetch(
instance: PrefetchableInstance, instance: PrefetchableInstance,
priority: PrefetchPriority.Default | PrefetchPriority.Intent priority: PrefetchPriority.Default | PrefetchPriority.Intent
) { ) {
const existingPrefetchTask = instance.prefetchTask // Ensures that app-router-instance is not compiled in the server bundle
if (typeof window !== 'undefined') {
if (!instance.isVisible) { const existingPrefetchTask = instance.prefetchTask
// Cancel any in-progress prefetch task. (If it already finished then this
// is a no-op.) if (!instance.isVisible) {
if (existingPrefetchTask !== null) { // Cancel any in-progress prefetch task. (If it already finished then this
cancelPrefetchTask(existingPrefetchTask) // is a no-op.)
if (existingPrefetchTask !== null) {
cancelPrefetchTask(existingPrefetchTask)
}
// We don't need to reset the prefetchTask to null upon cancellation; an
// old task object can be rescheduled with reschedulePrefetchTask. This is a
// micro-optimization but also makes the code simpler (don't need to
// worry about whether an old task object is stale).
return
} }
// We don't need to reset the prefetchTask to null upon cancellation; an
// old task object can be rescheduled with reschedulePrefetchTask. This is a
// micro-optimization but also makes the code simpler (don't need to
// worry about whether an old task object is stale).
return
}
if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) { if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) {
// The old prefetch implementation does not have different priority levels. // The old prefetch implementation does not have different priority levels.
// Just schedule a new prefetch task. // Just schedule a new prefetch task.
prefetchWithOldCacheImplementation(instance) prefetchWithOldCacheImplementation(instance)
return return
} }
const appRouterState = getCurrentAppRouterState() const { getCurrentAppRouterState } =
if (appRouterState !== null) { require('./app-router-instance') as typeof import('./app-router-instance')
const treeAtTimeOfPrefetch = appRouterState.tree
if (existingPrefetchTask === null) { const appRouterState = getCurrentAppRouterState()
// Initiate a prefetch task. if (appRouterState !== null) {
const nextUrl = appRouterState.nextUrl const treeAtTimeOfPrefetch = appRouterState.tree
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl) if (existingPrefetchTask === null) {
instance.prefetchTask = scheduleSegmentPrefetchTask( // Initiate a prefetch task.
cacheKey, const nextUrl = appRouterState.nextUrl
treeAtTimeOfPrefetch, const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.fetchStrategy, instance.prefetchTask = scheduleSegmentPrefetchTask(
priority, cacheKey,
null treeAtTimeOfPrefetch,
) instance.fetchStrategy,
} else { priority,
// We already have an old task object that we can reschedule. This is null
// effectively the same as canceling the old task and creating a new one. )
reschedulePrefetchTask( } else {
existingPrefetchTask, // We already have an old task object that we can reschedule. This is
treeAtTimeOfPrefetch, // effectively the same as canceling the old task and creating a new one.
instance.fetchStrategy, reschedulePrefetchTask(
priority existingPrefetchTask,
) treeAtTimeOfPrefetch,
instance.fetchStrategy,
priority
)
}
} }
} }
} }
......
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { createPrefetchURL } from '../app-router' import { createPrefetchURL } from '../app-router-utils'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { schedulePrefetchTask } from './scheduler' import { schedulePrefetchTask } from './scheduler'
import { import {
......
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