Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
0400a937
Unverified
Commit
0400a937
authored
Feb 10, 2026
by
Sam Selikoff
Committed by
GitHub
Feb 10, 2026
Browse files
Options
Browse Files
Download
Plain Diff
Merge branch 'canary' into feat/staletime-segment-config
parents
3f5f6a9c
53481e3f
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
174 additions
and
39 deletions
+174
-39
unstable_cache.mdx
docs/01-app/03-api-reference/04-functions/unstable_cache.mdx
+3
-1
app-router.tsx
packages/next/src/client/components/app-router.tsx
+21
-15
clone-response.ts
packages/next/src/server/lib/clone-response.ts
+18
-18
load-manifest.external.ts
packages/next/src/server/load-manifest.external.ts
+1
-1
route-module.ts
packages/next/src/server/route-modules/route-module.ts
+4
-1
page.tsx
...egment-cache/memory-pressure/app/memory-pressure/page.tsx
+2
-2
segment-cache-memory-pressure.test.ts
...che/memory-pressure/segment-cache-memory-pressure.test.ts
+125
-1
No files found.
docs/01-app/03-api-reference/04-functions/unstable_cache.mdx
View file @
0400a937
...
...
@@ -3,7 +3,9 @@ title: unstable_cache
description
:
API
Reference
for
the
unstable_cache
function
.
---
>
**
Warning
:**
This
API
will
be
replaced
by
[
`use cache`
](
/
docs
/
app
/
api
-
reference
/
directives
/
use
-
cache
)
when
it
reaches
stability
.
>
**
Note
:**
>
This
API
has
been
replaced
by
[
`use cache`
](
/
docs
/
app
/
api
-
reference
/
directives
/
use
-
cache
)
in
Next
.
js
16.
>
We
recommend
opting
into
[
Cache
Components
](
/
docs
/
app
/
getting
-
started
/
cache
-
components
)
and
replacing
`unstable_cache`
with
the
`use cache`
directive
.
`unstable_cache`
allows
you
to
cache
the
results
of
expensive
operations
,
like
database
queries
,
and
reuse
them
across
multiple
requests
.
...
...
packages/next/src/client/components/app-router.tsx
View file @
0400a937
...
...
@@ -523,7 +523,7 @@ function Router({
return
(
<>
<
HistoryUpdater
appRouterState=
{
state
}
/>
<
RuntimeStyles
/>
{
process
.
env
.
TURBOPACK
?
null
:
<
RuntimeStylesForWebpack
/>
}
<
NavigationPromisesContext
.
Provider
value=
{
instrumentedNavigationPromises
}
>
...
...
@@ -583,24 +583,30 @@ export default function AppRouter({
)
}
const
runtimeStyles
=
new
Set
<
string
>
()
let
runtimeStyleChanged
=
new
Set
<
()
=>
void
>
()
globalThis
.
_N_E_STYLE_LOAD
=
function
(
href
:
string
)
{
let
len
=
runtimeStyles
.
size
runtimeStyles
.
add
(
href
)
if
(
runtimeStyles
.
size
!==
len
)
{
runtimeStyleChanged
.
forEach
((
cb
)
=>
cb
())
let
runtimeStyles
:
Set
<
string
>
|
undefined
let
runtimeStyleChanged
:
Set
<
()
=>
void
>
|
undefined
if
(
!
process
.
env
.
TURBOPACK
&&
typeof
window
!==
'undefined'
)
{
runtimeStyles
=
new
Set
<
string
>
()
runtimeStyleChanged
=
new
Set
<
()
=>
void
>
()
globalThis
.
_N_E_STYLE_LOAD
=
function
(
href
:
string
)
{
if
(
!
runtimeStyles
||
!
runtimeStyleChanged
)
return
Promise
.
resolve
()
let
len
=
runtimeStyles
.
size
runtimeStyles
.
add
(
href
)
if
(
runtimeStyles
.
size
!==
len
)
{
runtimeStyleChanged
.
forEach
((
cb
)
=>
cb
())
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return
Promise
.
resolve
()
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return
Promise
.
resolve
()
}
function
RuntimeStyles
()
{
function
RuntimeStyles
ForWebpack
()
{
const
[,
forceUpdate
]
=
React
.
useState
(
0
)
const
renderedStylesSize
=
runtimeStyles
.
size
const
renderedStylesSize
=
runtimeStyles
?.
size
??
0
useEffect
(()
=>
{
if
(
!
runtimeStyles
||
!
runtimeStyleChanged
)
return
const
changed
=
()
=>
forceUpdate
((
c
)
=>
c
+
1
)
runtimeStyleChanged
.
add
(
changed
)
if
(
renderedStylesSize
!==
runtimeStyles
.
size
)
{
...
...
@@ -612,7 +618,7 @@ function RuntimeStyles() {
},
[
renderedStylesSize
,
forceUpdate
])
const
dplId
=
getDeploymentIdQueryOrEmptyString
()
return
[...
runtimeStyles
].
map
((
href
,
i
)
=>
(
return
[...
(
runtimeStyles
||
[])
].
map
((
href
,
i
)
=>
(
<
link
key=
{
i
}
rel=
"stylesheet"
...
...
packages/next/src/server/lib/clone-response.ts
View file @
0400a937
...
...
@@ -46,24 +46,6 @@ export function cloneResponse(original: Response): [Response, Response] {
writable
:
false
,
})
// The Fetch Standard allows users to skip consuming the response body by
// relying on garbage collection to release connection resources.
// https://github.com/nodejs/undici?tab=readme-ov-file#garbage-collection
//
// To cancel the stream you then need to cancel both resulting branches.
// Teeing a stream will generally lock it for the duration, preventing other
// readers from locking it.
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee
// cloned2 is stored in a react cache and cloned for subsequent requests.
// It is the original request, and is is garbage collected by a
// FinalizationRegistry in Undici, but since we're tee-ing the stream
// ourselves, we need to cancel clone1's stream (the response returned from
// our dedupe fetch) when clone1 is reclaimed, otherwise we leak memory.
if
(
registry
&&
cloned1
.
body
)
{
registry
.
register
(
cloned1
,
new
WeakRef
(
cloned1
.
body
))
}
const
cloned2
=
new
Response
(
body2
,
{
status
:
original
.
status
,
statusText
:
original
.
statusText
,
...
...
@@ -78,5 +60,23 @@ export function cloneResponse(original: Response): [Response, Response] {
writable
:
false
,
})
// The Fetch Standard allows users to skip consuming the response body by
// relying on garbage collection to release connection resources.
// https://github.com/nodejs/undici?tab=readme-ov-file#garbage-collection
//
// To cancel the stream you then need to cancel both resulting branches.
// Teeing a stream will generally lock it for the duration, preventing other
// readers from locking it.
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee
if
(
registry
)
{
if
(
cloned1
.
body
)
{
registry
.
register
(
cloned1
,
new
WeakRef
(
cloned1
.
body
))
}
if
(
cloned2
.
body
)
{
registry
.
register
(
cloned2
,
new
WeakRef
(
cloned2
.
body
))
}
}
return
[
cloned1
,
cloned2
]
}
packages/next/src/server/load-manifest.external.ts
View file @
0400a937
...
...
@@ -122,7 +122,7 @@ export function loadManifestFromRelativePath<T extends object>({
projectDir
:
string
distDir
:
string
manifest
:
string
shouldCache
?
:
boolean
shouldCache
:
boolean
cache
?:
Map
<
string
,
unknown
>
skipParse
?:
boolean
handleMissing
?:
boolean
...
...
packages/next/src/server/route-modules/route-module.ts
View file @
0400a937
...
...
@@ -347,6 +347,7 @@ export abstract class RouteModule<
:
loadManifestFromRelativePath
<
RequiredServerFilesManifest
>
({
projectDir
,
distDir
:
this
.
distDir
,
shouldCache
:
true
,
manifest
:
`
${
SERVER_FILES_MANIFEST
}
.json`
,
}),
this
.
isDev
...
...
@@ -356,11 +357,13 @@ export abstract class RouteModule<
distDir
:
this
.
distDir
,
manifest
:
BUILD_ID_FILE
,
skipParse
:
true
,
shouldCache
:
true
,
}),
loadManifestFromRelativePath
<
any
>
({
projectDir
,
distDir
:
this
.
distDir
,
manifest
:
DYNAMIC_CSS_MANIFEST
,
shouldCache
:
!
this
.
isDev
,
handleMissing
:
true
,
}),
]
...
...
@@ -628,7 +631,7 @@ export abstract class RouteModule<
// onRequestError below
ensureInstrumentationRegistered
(
absoluteProjectDir
,
this
.
distDir
)
}
const
manifests
=
await
this
.
loadManifests
(
srcPage
,
absoluteProjectDir
)
const
manifests
=
this
.
loadManifests
(
srcPage
,
absoluteProjectDir
)
const
{
routesManifest
,
prerenderManifest
,
serverFilesManifest
}
=
manifests
const
{
basePath
,
i18n
,
rewrites
}
=
routesManifest
...
...
test/e2e/app-dir/segment-cache/memory-pressure/app/memory-pressure/page.tsx
View file @
0400a937
...
...
@@ -4,7 +4,7 @@ import { useState } from 'react'
import
{
useRouter
}
from
'next/navigation'
function
Tab0
()
{
return
'Intentionally empty'
return
<
p
id=
"tab-0-content"
>
Intentionally empty
</
p
>
}
function
Tab1
()
{
...
...
@@ -111,7 +111,7 @@ export default function MemoryPressure() {
Tab 2
</
label
>
</
div
>
<
div
>
{
tab
}
</
div
>
<
div
id=
"tab-content"
>
{
tab
}
</
div
>
</
form
>
)
}
test/e2e/app-dir/segment-cache/memory-pressure/segment-cache-memory-pressure.test.ts
View file @
0400a937
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
createRouterAct
}
from
'router-act'
import
type
{
CDPSession
,
Page
,
Request
as
PlaywrightRequest
}
from
'playwright'
describe
(
'segment cache memory pressure'
,
()
=>
{
const
{
next
,
isNextDev
}
=
nextTestSetup
({
files
:
__dirname
,
})
if
(
isNextDev
)
{
test
(
'disabled in development
/ deployment
'
,
()
=>
{})
test
(
'disabled in development'
,
()
=>
{})
return
}
...
...
@@ -53,4 +54,127 @@ describe('segment cache memory pressure', () => {
}
)
})
it
(
'does not leak memory when repeatedly triggering prefetches'
,
async
()
=>
{
let
cdpSession
:
CDPSession
let
page
:
Page
const
browser
=
await
next
.
browser
(
'/memory-pressure'
,
{
async
beforePageLoad
(
p
:
Page
)
{
page
=
p
cdpSession
=
await
page
.
context
().
newCDPSession
(
page
)
await
cdpSession
.
send
(
'HeapProfiler.enable'
)
},
})
const
tab0Radio
=
await
browser
.
elementByCss
(
'input[type="radio"][value="0"]'
)
const
tab2Radio
=
await
browser
.
elementByCss
(
'input[type="radio"][value="2"]'
)
const
totalCycles
=
10
const
measurements
:
number
[]
=
[]
for
(
let
i
=
0
;
i
<
totalCycles
;
i
++
)
{
// Switch to Tab 2 (links mount, prefetches are triggered)
const
prefetchesSettled
=
waitForPrefetchesToSettle
(
page
)
await
tab2Radio
.
click
()
await
browser
.
waitForElementByCss
(
'#tab-content a'
)
await
prefetchesSettled
// Switch back to Tab 0 (links unmount)
await
tab0Radio
.
click
()
await
browser
.
waitForElementByCss
(
'#tab-0-content'
)
measurements
.
push
(
await
getHeapMB
(
cdpSession
))
}
// Use linear regression on measurements (skipping the first as warmup)
// to compute the slope (MB/cycle). If evicted prefetch entries are not
// properly garbage-collected, the heap will grow steadily across cycles
// instead of plateauing.
const
afterWarmup
=
measurements
.
slice
(
1
)
const
n
=
afterWarmup
.
length
let
sumX
=
0
let
sumY
=
0
let
sumXY
=
0
let
sumXX
=
0
for
(
let
j
=
0
;
j
<
n
;
j
++
)
{
sumX
+=
j
sumY
+=
afterWarmup
[
j
]
sumXY
+=
j
*
afterWarmup
[
j
]
sumXX
+=
j
*
j
}
const
growthPerCycle
=
(
n
*
sumXY
-
sumX
*
sumY
)
/
(
n
*
sumXX
-
sumX
*
sumX
)
try
{
expect
(
growthPerCycle
).
toBeLessThan
(
0.1
)
}
catch
(
e
)
{
throw
new
Error
(
`Heap grew
${
growthPerCycle
.
toFixed
(
3
)}
MB/cycle.\n`
+
`Measurements (MB):
${
measurements
.
map
((
m
)
=>
m
.
toFixed
(
2
)).
join
(
', '
)}
`
)
}
},
120
_000
)
})
async
function
getHeapMB
(
cdpSession
:
CDPSession
):
Promise
<
number
>
{
await
cdpSession
.
send
(
'HeapProfiler.collectGarbage'
)
await
cdpSession
.
send
(
'HeapProfiler.collectGarbage'
)
const
{
usedSize
}
=
await
cdpSession
.
send
(
'Runtime.getHeapUsage'
)
return
usedSize
/
1024
/
1024
}
/**
* Returns a promise that resolves once all in-flight prefetch requests have
* received responses and no new ones have been initiated for `quietMs`. Must be
* called *before* the action that triggers prefetches so that no requests are
* missed.
*/
function
waitForPrefetchesToSettle
(
page
:
Page
,
quietMs
=
200
):
Promise
<
void
>
{
let
inFlight
=
0
let
resolve
:
()
=>
void
let
timer
:
ReturnType
<
typeof
setTimeout
>
|
null
=
null
const
promise
=
new
Promise
<
void
>
((
r
)
=>
{
resolve
=
r
})
function
done
()
{
page
.
off
(
'request'
,
onRequest
)
page
.
off
(
'requestfinished'
,
onRequestDone
)
page
.
off
(
'requestfailed'
,
onRequestDone
)
resolve
()
}
function
check
()
{
if
(
inFlight
===
0
)
{
if
(
timer
)
{
clearTimeout
(
timer
)
}
timer
=
setTimeout
(
done
,
quietMs
)
}
}
function
onRequest
(
req
:
PlaywrightRequest
)
{
if
(
req
.
headers
()[
'next-router-segment-prefetch'
])
{
inFlight
++
if
(
timer
)
{
clearTimeout
(
timer
)
}
}
}
function
onRequestDone
(
req
:
PlaywrightRequest
)
{
if
(
req
.
headers
()[
'next-router-segment-prefetch'
])
{
inFlight
--
check
()
}
}
page
.
on
(
'request'
,
onRequest
)
page
.
on
(
'requestfinished'
,
onRequestDone
)
page
.
on
(
'requestfailed'
,
onRequestDone
)
return
promise
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment