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
18f28a33
Commit
18f28a33
authored
Jan 03, 2026
by
Jimmy Lai
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
fix: clean up webpack eval wrapper in stack traces
parent
2f31831c
Show whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
30 additions
and
306 deletions
+30
-306
next-dev-server.webpack-config.js
packages/next/next-dev-server.webpack-config.js
+2
-0
node-stack-frames.ts
packages/next/src/server/dev/node-stack-frames.ts
+23
-1
bytecode-cache.ts
packages/next/src/server/lib/bytecode-cache.ts
+0
-289
start-server-with-cache.ts
packages/next/src/server/lib/start-server-with-cache.ts
+5
-16
No files found.
packages/next/next-dev-server.webpack-config.js
View file @
18f28a33
...
@@ -194,6 +194,8 @@ module.exports = ({ dev }) => {
...
@@ -194,6 +194,8 @@ module.exports = ({ dev }) => {
path
:
path
.
join
(
__dirname
,
'dist/compiled/dev-server'
),
path
:
path
.
join
(
__dirname
,
'dist/compiled/dev-server'
),
filename
:
'[name].js'
,
filename
:
'[name].js'
,
libraryTarget
:
'commonjs2'
,
libraryTarget
:
'commonjs2'
,
// Use absolute paths in source maps so error formatting can compute correct relative paths
devtoolModuleFilenameTemplate
:
'[absolute-resource-path]'
,
},
},
devtool
:
'source-map'
,
devtool
:
'source-map'
,
optimization
:
{
optimization
:
{
...
...
packages/next/src/server/dev/node-stack-frames.ts
View file @
18f28a33
import
{
parse
}
from
'next/dist/compiled/stacktrace-parser'
import
{
parse
}
from
'next/dist/compiled/stacktrace-parser'
import
type
{
StackFrame
}
from
'next/dist/compiled/stacktrace-parser'
import
type
{
StackFrame
}
from
'next/dist/compiled/stacktrace-parser'
import
path
from
'path'
import
url
from
'url'
import
{
import
{
decorateServerError
,
decorateServerError
,
type
ErrorSourceType
,
type
ErrorSourceType
,
...
@@ -29,6 +31,25 @@ function getFilesystemFrame(frame: StackFrame): StackFrame {
...
@@ -29,6 +31,25 @@ function getFilesystemFrame(frame: StackFrame): StackFrame {
return f
return f
}
}
/**
* Convert a file path to a path relative to the current working directory.
*/
function toRelativePath(filePath: string): string {
if (filePath.startsWith('
file
:
//')) {
try
{
filePath
=
url
.
fileURLToPath
(
filePath
)
}
catch
{
// Invalid file URL, use as-is
}
}
if
(
path
.
isAbsolute
(
filePath
))
{
return
path
.
relative
(
process
.
cwd
(),
filePath
)
}
return
filePath
}
export
function
getServerError
(
error
:
Error
,
type
:
ErrorSourceType
):
Error
{
export
function
getServerError
(
error
:
Error
,
type
:
ErrorSourceType
):
Error
{
if
(
error
.
name
===
'TurbopackInternalError'
)
{
if
(
error
.
name
===
'TurbopackInternalError'
)
{
// If this is an internal Turbopack error we shouldn't show internal details
// If this is an internal Turbopack error we shouldn't show internal details
...
@@ -54,7 +75,8 @@ export function getServerError(error: Error, type: ErrorSourceType): Error {
...
@@ -54,7 +75,8 @@ export function getServerError(error: Error, type: ErrorSourceType): Error {
.
map
((
f
)
=>
{
.
map
((
f
)
=>
{
let
str
=
` at
${
f
.
methodName
}
`
let
str
=
` at
${
f
.
methodName
}
`
if
(
f
.
file
)
{
if
(
f
.
file
)
{
let
loc
=
f
.
file
// Convert to relative path for cleaner output
let
loc
=
toRelativePath
(
f
.
file
)
if
(
f
.
lineNumber
)
{
if
(
f
.
lineNumber
)
{
loc
+=
`:
${
f
.
lineNumber
}
`
loc
+=
`:
${
f
.
lineNumber
}
`
if
(
f
.
column
)
{
if
(
f
.
column
)
{
...
...
packages/next/src/server/lib/bytecode-cache.ts
deleted
100644 → 0
View file @
2f31831c
/**
* V8 Bytecode Cache for Dev Server Bundle
*
* This module provides bytecode caching specifically for the bundled dev server,
* avoiding the overhead of parsing large JavaScript files on every startup.
*
* Unlike Node.js's NODE_COMPILE_CACHE which caches everything (including user code),
* this only caches the dev server bundle which doesn't change between restarts.
*
* Important: Bytecode is saved AFTER a warmup period to capture JIT-optimized code.
* V8's TurboFan compiler optimizes hot code paths, and we want to cache that.
*
* Debug logging: Set DEBUG=next:bytecode-cache to see cache hit/miss info
*/
import
{
Script
}
from
'vm'
import
{
createRequire
}
from
'module'
import
{
readFileSync
,
writeFileSync
,
existsSync
,
mkdirSync
,
statSync
,
}
from
'fs'
import
{
createHash
}
from
'crypto'
import
{
join
,
dirname
,
basename
}
from
'path'
import
{
tmpdir
}
from
'os'
import
setupDebug
from
'next/dist/compiled/debug'
const
debug
=
setupDebug
(
'next:bytecode-cache'
)
const
CACHE_VERSION
=
2
// How long to wait before saving bytecode (allows JIT warmup)
const
WARMUP_DELAY_MS
=
10
_000
interface
CacheMetadata
{
version
:
number
sourceHash
:
string
nodeVersion
:
string
v8Version
:
string
mtime
:
number
}
/**
* Get the cache directory for bytecode files
*/
function
getCacheDir
():
string
{
// Use .next/cache/bytecode if in a project, otherwise use temp
const
projectCacheDir
=
join
(
process
.
cwd
(),
'.next'
,
'cache'
,
'bytecode'
)
if
(
existsSync
(
join
(
process
.
cwd
(),
'.next'
)))
{
return
projectCacheDir
}
// Fallback to a temp location (use os.tmpdir() for cross-platform support)
return
join
(
tmpdir
(),
'next-bytecode-cache'
,
process
.
version
)
}
/**
* Generate a hash of the source file for cache validation
*/
function
hashSource
(
source
:
string
):
string
{
return
createHash
(
'sha256'
).
update
(
source
).
digest
(
'hex'
).
slice
(
0
,
16
)
}
/**
* Get the cache file paths for a given module
*/
function
getCachePaths
(
modulePath
:
string
,
cacheDir
:
string
):
{
bytecode
:
string
;
metadata
:
string
}
{
const
moduleHash
=
createHash
(
'sha256'
)
.
update
(
modulePath
)
.
digest
(
'hex'
)
.
slice
(
0
,
16
)
return
{
bytecode
:
join
(
cacheDir
,
`
${
moduleHash
}
.bytecode`
),
metadata
:
join
(
cacheDir
,
`
${
moduleHash
}
.json`
),
}
}
/**
* Check if cached bytecode is valid
*/
function
isCacheValid
(
metadata
:
CacheMetadata
,
sourceHash
:
string
,
sourceMtime
:
number
):
boolean
{
return
(
metadata
.
version
===
CACHE_VERSION
&&
metadata
.
sourceHash
===
sourceHash
&&
metadata
.
nodeVersion
===
process
.
version
&&
metadata
.
v8Version
===
(
process
.
versions
.
v8
||
''
)
&&
metadata
.
mtime
===
sourceMtime
)
}
// Track scripts that need deferred cache saving after warmup
const
pendingCacheSaves
:
Array
<
{
script
:
Script
bytecodePath
:
string
metadataPath
:
string
sourceHash
:
string
sourceMtime
:
number
cacheDir
:
string
}
>
=
[]
// Track which bytecode paths are already pending to avoid duplicates
const
pendingBytecodePaths
=
new
Set
<
string
>
()
let
warmupScheduled
=
false
/**
* Schedule deferred bytecode cache saves after JIT warmup
*/
function
scheduleDeferredCacheSave
():
void
{
if
(
warmupScheduled
||
pendingCacheSaves
.
length
===
0
)
return
warmupScheduled
=
true
debug
(
'scheduling bytecode cache save after %dms warmup'
,
WARMUP_DELAY_MS
)
setTimeout
(()
=>
{
for
(
const
pending
of
pendingCacheSaves
)
{
try
{
// Use createCachedData() to get JIT-optimized bytecode
const
cachedData
=
pending
.
script
.
createCachedData
()
if
(
cachedData
&&
cachedData
.
length
>
0
)
{
mkdirSync
(
pending
.
cacheDir
,
{
recursive
:
true
})
writeFileSync
(
pending
.
bytecodePath
,
cachedData
)
writeFileSync
(
pending
.
metadataPath
,
JSON
.
stringify
({
version
:
CACHE_VERSION
,
sourceHash
:
pending
.
sourceHash
,
nodeVersion
:
process
.
version
,
v8Version
:
process
.
versions
.
v8
||
''
,
mtime
:
pending
.
sourceMtime
,
}
satisfies
CacheMetadata
)
)
debug
(
'wrote bytecode cache (%d KB) to %s'
,
Math
.
round
(
cachedData
.
length
/
1024
),
pending
.
bytecodePath
)
}
}
catch
(
err
)
{
debug
(
'failed to write bytecode cache: %s'
,
err
)
}
}
pendingCacheSaves
.
length
=
0
pendingBytecodePaths
.
clear
()
warmupScheduled
=
false
// Reset flag to allow future cache saves
},
WARMUP_DELAY_MS
).
unref
()
// unref so it doesn't keep the process alive
}
/**
* Load a module with bytecode caching
*
* This function:
* 1. Checks if valid cached bytecode exists
* 2. If yes, loads using cached bytecode (faster)
* 3. If no, compiles the script and schedules bytecode save after JIT warmup
*
* The deferred save captures JIT-optimized bytecode from V8's TurboFan compiler,
* resulting in faster execution on subsequent startups.
*
* @param modulePath - Absolute path to the JavaScript file
* @returns The module exports
*/
export
function
loadWithBytecodeCache
(
modulePath
:
string
):
any
{
const
cacheDir
=
getCacheDir
()
const
{
bytecode
:
bytecodePath
,
metadata
:
metadataPath
}
=
getCachePaths
(
modulePath
,
cacheDir
)
// Read source file
const
source
=
readFileSync
(
modulePath
,
'utf-8'
)
const
sourceHash
=
hashSource
(
source
)
const
sourceMtime
=
statSync
(
modulePath
).
mtimeMs
let
cachedData
:
Buffer
|
undefined
let
hadValidCache
=
false
const
moduleBasename
=
basename
(
modulePath
)
// Try to load cached bytecode
if
(
existsSync
(
metadataPath
)
&&
existsSync
(
bytecodePath
))
{
try
{
const
metadata
:
CacheMetadata
=
JSON
.
parse
(
readFileSync
(
metadataPath
,
'utf-8'
)
)
if
(
isCacheValid
(
metadata
,
sourceHash
,
sourceMtime
))
{
cachedData
=
readFileSync
(
bytecodePath
)
hadValidCache
=
true
debug
(
'bytecode cache HIT for %s (%d KB)'
,
moduleBasename
,
Math
.
round
(
cachedData
.
length
/
1024
)
)
}
else
{
debug
(
'bytecode cache STALE for %s (version/hash mismatch)'
,
moduleBasename
)
}
}
catch
{
debug
(
'bytecode cache INVALID for %s (corrupted)'
,
moduleBasename
)
}
}
else
{
debug
(
'bytecode cache MISS for %s (no cache file)'
,
moduleBasename
)
}
// Wrap source in a function to capture exports
const
wrappedSource
=
`(function(exports, require, module, __filename, __dirname) {
${
source
}
});`
// Create script with cached bytecode if available
const
script
=
new
Script
(
wrappedSource
,
{
filename
:
modulePath
,
cachedData
,
})
// Check if V8 rejected the cached data despite metadata validation passing
// This can happen due to corruption, platform incompatibility, or other
// V8-internal reasons beyond version mismatches. If rejected, we need to
// regenerate the cache to avoid infinite recompilation on every startup.
if
(
script
.
cachedDataRejected
)
{
hadValidCache
=
false
debug
(
'bytecode cache REJECTED for %s (V8 validation failed)'
,
moduleBasename
)
}
// If no valid cache, schedule deferred save after JIT warmup
// Only add to pending saves if this bytecode path is not already pending
// This prevents duplicate saves for the same module within a process
if
(
!
hadValidCache
&&
!
pendingBytecodePaths
.
has
(
bytecodePath
))
{
pendingCacheSaves
.
push
({
script
,
bytecodePath
,
metadataPath
,
sourceHash
,
sourceMtime
,
cacheDir
,
})
pendingBytecodePaths
.
add
(
bytecodePath
)
scheduleDeferredCacheSave
()
}
// Execute the script
const
compiledWrapper
=
script
.
runInThisContext
()
// Create module-like object
const
moduleObj
=
{
exports
:
{}
}
// Create a require function scoped to the module being loaded
// This ensures relative requires resolve correctly relative to the module's location
const
moduleRequire
=
createRequire
(
modulePath
)
compiledWrapper
(
moduleObj
.
exports
,
moduleRequire
,
moduleObj
,
modulePath
,
dirname
(
modulePath
)
)
return
moduleObj
.
exports
}
/**
* Check if bytecode caching is enabled
*/
export
function
isBytecodeCacheEnabled
():
boolean
{
return
process
.
env
.
NEXT_DISABLE_BYTECODE_CACHE
!==
'1'
}
/**
* Clear the bytecode cache
*/
export
function
clearBytecodeCache
():
void
{
const
cacheDir
=
getCacheDir
()
if
(
existsSync
(
cacheDir
))
{
const
{
rmSync
}
=
require
(
'fs'
)
as
typeof
import
(
'fs'
)
rmSync
(
cacheDir
,
{
recursive
:
true
,
force
:
true
})
}
}
packages/next/src/server/lib/start-server-with-cache.ts
View file @
18f28a33
/**
/**
* Start Server Entry Point
with Bytecode Caching
* Start Server Entry Point
for Bundled Dev Server
*
*
* This
is the entry point for the dev server that uses V8 bytecode caching
* This
module provides a unified entry point that can load either the bundled
*
to speed up loading of the bundled dev server on subsequent startups
.
*
or unbundled dev server based on environment configuration
.
*
*
* Environment variables:
* Environment variables:
* NEXT_DISABLE_BYTECODE_CACHE=1 - Disable bytecode caching
* NEXT_USE_UNBUNDLED_SERVER=1 - Use unbundled server instead (for development)
* NEXT_USE_UNBUNDLED_SERVER=1 - Use unbundled server instead
*/
*/
import
path
from
'path'
import
path
from
'path'
import
{
isBytecodeCacheEnabled
,
loadWithBytecodeCache
}
from
'./bytecode-cache'
// Determine which server to load
// Determine which server to load
const
useBundled
=
process
.
env
.
NEXT_USE_UNBUNDLED_SERVER
!==
'1'
const
useBundled
=
process
.
env
.
NEXT_USE_UNBUNDLED_SERVER
!==
'1'
const
useBytecodeCache
=
isBytecodeCacheEnabled
()
&&
useBundled
const
serverPath
=
useBundled
const
serverPath
=
useBundled
?
path
.
join
(
__dirname
,
'../../compiled/dev-server/start-server.js'
)
?
path
.
join
(
__dirname
,
'../../compiled/dev-server/start-server.js'
)
:
path
.
join
(
__dirname
,
'./start-server.js'
)
:
path
.
join
(
__dirname
,
'./start-server.js'
)
// Load the server module
// Load the server module
let
serverModule
:
typeof
import
(
'./start-server'
)
const
serverModule
:
typeof
import
(
'./start-server'
)
=
require
(
serverPath
)
if
(
useBytecodeCache
)
{
// Use bytecode caching for faster subsequent loads
serverModule
=
loadWithBytecodeCache
(
serverPath
)
}
else
{
// Regular require
serverModule
=
require
(
serverPath
)
}
// Re-export everything from the server module
// Re-export everything from the server module
export
const
{
startServer
,
getRequestHandlers
}
=
serverModule
export
const
{
startServer
,
getRequestHandlers
}
=
serverModule
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