image-component.js: deviceSizes.sort() crashes on frozen array in production SSR (Next.js 16)
Link to the code that reproduces this issue
https://github.com/AP-Forever/repo-test
To Reproduce
This only happens in production SSR (not in next dev). In production, Next.js (via the got library’s deepFreeze) freezes the config object coming from next.config.js. Therefore .sort() throws: TypeError: Cannot assign to read only property '0' of object
Current vs. Expected behavior
Affects Next.js 16.x in production/SSR only (not dev mode) image-component.js line 246: c.deviceSizes.sort(...) mutates in place Line 247: c.qualities?.sort(...) has the same problem Config arrays are frozen in production, so .sort() throws TypeError: Cannot assign to read only property '0' Fix is trivial: [...c.deviceSizes].sort(...) and [...c.qualities].sort(...)
Found out using an interceptor
=== SORT CRASH STACK === Error: at Array.sort (/var/task/src/rendering/sites/waterset-mobility-fees/.next/server/pages/[[...path]].js:1:6349) at /var/task/src/rendering/node_modules/next/dist/client/image-component.js:246:43 at Object.useMemo (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:3639:16) at exports.useMemo (/var/task/src/rendering/node_modules/react/cjs/react.production.js:514:33) at /var/task/src/rendering/node_modules/next/dist/client/image-component.js:240:39 at renderWithHooks (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:4747:18) at renderElement (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5293:18) at retryNode (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5603:16) at renderNodeDestructive (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5397:7) at finishFunctionComponent (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:4788:9)
Provide environment information
Operating System:
Platform: win32
Arch: x64
Version: Windows 11 Pro
Available memory (MB): 65321
Available CPU cores: 16
Binaries:
Node: 24.15.0
npm: 11.12.1
Yarn: 1.22.22
pnpm: N/A
Relevant Packages:
next: 16.2.6 // There is a newer version (16.2.9) available, upgrade recommended!
eslint-config-next: 13.5.11
react: 19.2.6
react-dom: 19.2.6
typescript: 5.4.5
Which area(s) are affected? (Select all that apply)
Image (next/image)
Which stage(s) are affected? (Select all that apply)
Vercel (Deployed)
Additional context
No response
Thanks for the detailed report and reproduction repository. I'd like to investigate this issue and work on a fix. I'll start by reproducing the production SSR behavior and add a regression test to ensure frozen config arrays are handled correctly.
I can't really repro. Is there anything else missing here? A plugin? locally it builds and starts fine, and I deployed to Vercel too, no problem.
Not sure if this stack trace will help that I got from applying interceptor.
npm run start 2>&1 | grep -A 20 "FREEZING NUMBER ARRAY"
Trace: === FREEZING NUMBER ARRAY === [
408, 413, 429, 500,
502, 503, 504, 521,
522, 524
]
at C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\next\dist\server\node-environment-extensions\console-exit.js:22:95
at AsyncLocalStorage.run (node:internal/async_local_storage/async_context_frame:59:14)
at AsyncLocalStorage.exit (node:internal/async_local_storage/async_context_frame:70:17)
at console.trace (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\next\dist\server\node-environment-extensions\console-exit.js:22:71)
at console.trace (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\next\dist\server\node-environment-extensions\console-dim.external.js:263:47)
at Object.freeze (C:\Users\amitp\source\repos\*****************\src\rendering\sites\**sitename***\next.config.js:4:13)
at deepFreeze (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\got\dist\source\utils\deep-freeze.js:10:19)
at deepFreeze (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\got\dist\source\utils\deep-freeze.js:7:13)
at deepFreeze (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\got\dist\source\utils\deep-freeze.js:7:13)
at Object.deepFreeze [as default] (C:\Users\amitp\source\repos\*****************\src\rendering\node_modules\got\dist\source\utils\deep-freeze.js:7:13)
Node Version: v24.15.0
Config file:
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const sassAliases = {
'@sass': path.join(__dirname, 'src/assets/sass'),
'@fontawesome': path.join(__dirname, '../../node_modules/font-awesome'),
};
// Modern Dart Sass 2.0-compatible FileImporter replacing the legacy sass-alias API
const sassAliasImporter = {
findFileUrl(url) {
for (const [alias, aliasPath] of Object.entries(sassAliases)) {
if (url.startsWith(alias + '/') || url === alias) {
const resolved = path.join(aliasPath, url.slice(alias.length));
const candidates = [
resolved,
resolved + '.scss',
path.join(path.dirname(resolved), '_' + path.basename(resolved)),
path.join(path.dirname(resolved), '_' + path.basename(resolved)) + '.scss',
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return new URL('file:///' + candidate.replace(/\\/g, '/'));
}
}
return new URL('file:///' + resolved.replace(/\\/g, '/'));
}
}
return null;
},
};
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
transpilePackages: ['@***/shared', '@***/homefinder'],
experimental: {
externalDir: true,
},
sassOptions: {
includePaths: [
'../../node_modules', // Root node_modules
'./src/assets/sass', // Your sass directory
'./src/assets', // Assets directory
],
importers: [sassAliasImporter],
},
// Allow specifying a distinct distDir when concurrently running app in a container
distDir: process.env.NEXTJS_DIST_DIR || '.next',
i18n: {
// These are all the locales you want to support in your application.
// These should generally match (or at least be a subset of) those in Sitecore.
// DEMO TEAM CUSTOMIZATION - Remove unused languages and add some
locales: ['en', 'fr-CA', 'ja-JP'],
// END CUSTOMIZATION
// This is the locale that will be used when visiting a non-locale
// prefixed path e.g. `/styleguide`.
defaultLocale: process.env.DEFAULT_LANGUAGE || process.env.NEXT_PUBLIC_DEFAULT_LANGUAGE || 'en',
},
// Disable Strict Mode to avoid dev-only double mount/unmount side effects
// that interfere with Homefinder siteplan click/activation flow in host app.
reactStrictMode: false,
compiler: {
// Ensure proper JSX handling
reactRemoveProperties: process.env.NODE_ENV === 'production',
},
// use this configuration to ensure that only images from the whitelisted domains
// can be served from the Next.js Image Optimization API
// see https://nextjs.org/docs/app/api-reference/components/image#remotepatterns
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'edge*.**',
port: '',
},
{
protocol: 'https',
hostname: 'xmc-*.**',
port: '',
},
{
protocol: 'https',
hostname: 'feaas*.blob.core.windows.net',
port: '',
},
],
dangerouslyAllowSVG: true,
},
async rewrites() {
return [
// healthz check
{
source: '/healthz',
destination: '/api/healthz',
},
// FEaaS render route
{
source: '/feaas-render',
destination: '/api/editing/feaas/render',
},
// robots route
{
source: '/robots.txt',
destination: '/api/robots',
},
// sitemap route
{
source: '/sitemap:id([\\w-]{0,}).xml',
destination: '/api/sitemap',
},
];
},
async headers() {
return [
{
// FIX: COEP Allows Embedded opt-in e.g. `google-tag-manager`
source: '/(.*)',
headers: [
{
key: 'Cross-Origin-Resource-Policy',
value: 'cross-origin',
},
{
key: 'Cross-Origin-Embedder-Policy',
value: 'credentialless',
},
],
},
];
},
webpack: (config, options) => {
// FEAAS: Force use of CommonJS on the server to avoid dual package hazard.
// See https://nodejs.org/api/packages.html#dual-package-hazard
if (options.isServer) {
config.externals = [
{
'@sitecore-feaas/clientside/react': 'commonjs @sitecore-feaas/clientside/react',
'@sitecore/byoc': 'commonjs @sitecore/byoc',
'@sitecore/byoc/react': 'commonjs @sitecore/byoc/react',
},
...config.externals,
];
}
// GraphQL loaders
const homefinderRoot = path.resolve(__dirname, '../../packages/homefinder');
const homefinderSrc = path.resolve(__dirname, '../../packages/homefinder/src');
// Match Homefinder's SVG behavior so imports like `import Icon from './icon.svg'`
// resolve to React components when this package is transpiled in Base.
const fileLoaderRule = config.module.rules.find((rule) => rule.test?.test?.('.svg'));
if (fileLoaderRule) {
config.module.rules.push(
{
...fileLoaderRule,
test: /\.svg$/i,
resourceQuery: /url/,
},
{
test: /\.svg$/i,
resourceQuery: { not: [...(fileLoaderRule.resourceQuery?.not || []), /url/] },
use: ['@svgr/webpack'],
}
);
fileLoaderRule.exclude = /\.svg$/i;
}
// Resolve Homefinder's internal absolute imports like "components/*", "lib/*", "src/*".
config.resolve.modules = [homefinderRoot, homefinderSrc, ...(config.resolve.modules || [])];
// Rewrite Homefinder-only "@/*" imports to "src/*" so they resolve from homefinderRoot.
config.plugins.push(
new webpack.NormalModuleReplacementPlugin(/^@\/(.*)$/, (resource) => {
if (
resource.context &&
resource.context.includes(`${path.sep}packages${path.sep}homefinder`)
) {
resource.request = `src/${resource.request.slice(2)}`;
}
})
);
// Ensure Homefinder's `temp/*` imports resolve to Homefinder's generated config,
// not Base's `src/temp/*` (which does not include Mapbox settings).
config.plugins.push(
new webpack.NormalModuleReplacementPlugin(/^temp\/(.*)$/, (resource) => {
if (
resource.context &&
resource.context.includes(`${path.sep}packages${path.sep}homefinder`)
) {
resource.request = `src/temp/${resource.request.slice(5)}`;
}
})
);
return config;
},
};
module.exports = nextConfig;
I am using Sitecore Content SDK 2.1 with NextJS and deployed on Vercel.
MMm do you manually import the config into another file, or something like that? Anything more you could try to share about the issue? The repo you submitted doesn't show the error does it? I tried to just make a copy myself, and nada either.
We have a lot of packages and it is Mono-Repo architecture. We have about 7 sites in it.
I cannot really share that repo since it is for client.
Here is package.json for the site itself.
And here is the package.json for parent folder that hosts most of the shared packages across the sites.
Here is the architecture of folders
From my stack trace, it looked like the frozen array was being sent by "got" library at build time and at runtime NextJS was trying to sort it.
Well, Next.js itself doesn't freeze the deviceSizes, nor qualities.
There must be something else on your environment. Try to reproduce it on a clean project, the one you submitted for example. If you can't repro, it is a strong indicator that the issue in user space. Note that a patch here would also take time to trickle down, and require you to upgrade and such too. We have to get to the bottom of this first.
From my debugging, it was "got" library that sending frozen sizes and passing to image component and then Nextjs tries to sort it. That "got" library comes from dependency of "mapbox" library that we use in our implementation.
In any case, I believe NextJs should check for frozen array before sorting it for Image component to avoid this issue even if it was user specific.
What's the actual chain in which this happens? Who imports what, were, and how does that even end up impacting the default next/image config? Your shared next.config did not have these, deviceSort and qualities, so somehow got is getting all the way there?
This is the trace
Found out using an interceptor
=== SORT CRASH STACK === Error:
at Array.sort (/var/task/src/rendering/sites/waterset-mobility-fees/.next/server/pages/[[...path]].js:1:6349)
at /var/task/src/rendering/node_modules/next/dist/client/image-component.js:246:43
at Object.useMemo (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:3639:16)
at exports.useMemo (/var/task/src/rendering/node_modules/react/cjs/react.production.js:514:33)
at /var/task/src/rendering/node_modules/next/dist/client/image-component.js:240:39
at renderWithHooks (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:4747:18)
at renderElement (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5293:18)
at retryNode (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5603:16)
at renderNodeDestructive (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:5397:7)
at finishFunctionComponent (/var/task/src/rendering/node_modules/react-dom/cjs/react-dom-server.edge.production.js:4788:9)
I was able to extract this using an interceptor that I had put in in the layout.tsx file at the very top like this:
const originalSort = Array.prototype.sort;
Array.prototype.sort = function (...args) {
try {
return originalSort.apply(this, args);
} catch (e) {
console.error('=== SORT CRASH STACK ===', new Error().stack);
return originalSort.apply([...this], args); // don't crash, just log
}
};
That doesn't help all that much, cuz we don't know how you are using got. It is also interesting that, https://github.com/sindresorhus/got/blob/v11.8.6/source/utils/deep-freeze.ts is the last time got had its own deep-freeze. That's about 6 years old version.
It'd seem as if you have a custom server, or somehow import nextConfig into a module that does deepFreeze from got?
If you need other configs/files, kindly let me know. I will redact sensitive info and provide you with them.
Well, I don't need to see code, just need to understand, what do you use got for, what is its role here. Is it a third party dependency that in turn uses it?
As said above, got moved away from their deep-freeze util, about 6 years ago. Really considering whether this is an issue at all now. We can do some improvements to the .sort and such, but it is a stretch to call it an issue, we can't repro, and it uses outdated libraries, apparently.
We are using Mapbox sdk as we have a feature on implementation about interactive map. That SDK has a dependency on got library. It may not be an issue, but improving it should be done in my opinion.
What version of this Mapbox SDK?
I understand your concern, and suggestion, it is just also worth exploring whether or not the framework has to try/catch or check every operation before it does it. While looking at this, I think there was a small refactor that could be made for clarity but in general, if a 3rd party causes and issue like this one, we have to understand the mechanism first, and that is still rather unclear.
Edit: So they are still on version 11 there, https://github.com/mapbox/mapbox-sdk-js/blob/314e747d3e43cd5299a9b255c0cadb60940d9435/lib/node/node-layer.js#L30 - 🤔
Could you update the repro so it freezes images.deviceSizes / images.qualities directly in next.config.js, without the Sitecore/got path involved?
That would separate the Next image mutation from the integration that currently freezes the config. If that minimal case throws in next start, the fix is just making the .sort() calls non-mutating.
@barry166 wouldn't that, in a sense, force the bug? Then I could argue, this could be fixed with docs change or something similar. Reviewing my notes, I seem to have thought that OP forgot to do that, and I did it myself, and it still did not trigger, after which I posted here.