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 {
type LinkInstance,
} from '../components/links'
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { dispatchNavigateAction } from '../components/app-router-instance'
import {
FetchStrategy,
type PrefetchTaskFetchStrategy,
......@@ -221,47 +220,52 @@ function linkClicked(
scroll?: boolean,
onNavigate?: OnNavigateEventHandler
): void {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
// 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)
if (typeof window !== 'undefined') {
if (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
// ignore click for browser’s default behavior
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)
}
e.preventDefault()
// ignore click for browser’s default behavior
return
}
if (onNavigate) {
let isDefaultPrevented = false
e.preventDefault()
onNavigate({
preventDefault: () => {
isDefaultPrevented = true
},
})
if (onNavigate) {
let isDefaultPrevented = false
if (isDefaultPrevented) {
return
onNavigate({
preventDefault: () => {
isDefaultPrevented = true
},
})
if (isDefaultPrevented) {
return
}
}
}
React.startTransition(() => {
dispatchNavigateAction(
as || href,
replace ? 'replace' : 'push',
scroll ?? true,
linkInstanceRef.current
)
})
const { dispatchNavigateAction } =
require('../components/app-router-instance') as typeof import('../components/app-router-instance')
React.startTransition(() => {
dispatchNavigateAction(
as || href,
replace ? 'replace' : 'push',
scroll ?? true,
linkInstanceRef.current
)
})
}
}
function formatStringOrUrl(urlObjOrString: UrlObject | string): string {
......
......@@ -21,7 +21,7 @@ import {
} from './segment-cache'
import { dispatchAppRouterAction } from './use-action-queue'
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 type {
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, {
useEffect,
useMemo,
......@@ -25,8 +23,6 @@ import {
PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime'
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 { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
......@@ -53,47 +49,6 @@ const globalMutable: {
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({
appRouterState,
}: {
......
import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { getCurrentAppRouterState } from './app-router-instance'
import { createPrefetchURL } from './app-router'
import {
FetchStrategy,
isPrefetchTaskDirty,
......@@ -122,19 +120,26 @@ function observeVisibility(element: Element, instance: PrefetchableInstance) {
}
function coercePrefetchableUrl(href: string): URL | null {
try {
return createPrefetchURL(href)
} catch {
// createPrefetchURL sometimes throws an error if an invalid URL is
// provided, though I'm not sure if it's actually necessary.
// TODO: Consider removing the throw from the inner function, or change it
// to reportError. Or maybe the error isn't even necessary for automatic
// prefetches, just navigations.
const reportErrorFn =
typeof reportError === 'function' ? reportError : console.error
reportErrorFn(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
if (typeof window !== 'undefined') {
const { createPrefetchURL } =
require('./app-router-utils') as typeof import('./app-router-utils')
try {
return createPrefetchURL(href)
} catch {
// createPrefetchURL sometimes throws an error if an invalid URL is
// provided, though I'm not sure if it's actually necessary.
// TODO: Consider removing the throw from the inner function, or change it
// to reportError. Or maybe the error isn't even necessary for automatic
// 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
}
}
......@@ -274,51 +279,57 @@ function rescheduleLinkPrefetch(
instance: PrefetchableInstance,
priority: PrefetchPriority.Default | PrefetchPriority.Intent
) {
const existingPrefetchTask = instance.prefetchTask
if (!instance.isVisible) {
// Cancel any in-progress prefetch task. (If it already finished then this
// is a no-op.)
if (existingPrefetchTask !== null) {
cancelPrefetchTask(existingPrefetchTask)
// Ensures that app-router-instance is not compiled in the server bundle
if (typeof window !== 'undefined') {
const existingPrefetchTask = instance.prefetchTask
if (!instance.isVisible) {
// Cancel any in-progress prefetch task. (If it already finished then this
// 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) {
// The old prefetch implementation does not have different priority levels.
// Just schedule a new prefetch task.
prefetchWithOldCacheImplementation(instance)
return
}
if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) {
// The old prefetch implementation does not have different priority levels.
// Just schedule a new prefetch task.
prefetchWithOldCacheImplementation(instance)
return
}
const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) {
const treeAtTimeOfPrefetch = appRouterState.tree
if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const nextUrl = appRouterState.nextUrl
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
treeAtTimeOfPrefetch,
instance.fetchStrategy,
priority,
null
)
} else {
// We already have an old task object that we can reschedule. This is
// effectively the same as canceling the old task and creating a new one.
reschedulePrefetchTask(
existingPrefetchTask,
treeAtTimeOfPrefetch,
instance.fetchStrategy,
priority
)
const { getCurrentAppRouterState } =
require('./app-router-instance') as typeof import('./app-router-instance')
const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) {
const treeAtTimeOfPrefetch = appRouterState.tree
if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const nextUrl = appRouterState.nextUrl
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
treeAtTimeOfPrefetch,
instance.fetchStrategy,
priority,
null
)
} else {
// We already have an old task object that we can reschedule. This is
// effectively the same as canceling the old task and creating a new one.
reschedulePrefetchTask(
existingPrefetchTask,
treeAtTimeOfPrefetch,
instance.fetchStrategy,
priority
)
}
}
}
}
......
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 { schedulePrefetchTask } from './scheduler'
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