Skip to content

fix(image): port Next.js's next/legacy/image component - #4914

Open
james-elicx wants to merge 9 commits into
fix/image-loader-configfrom
fix/legacy-image-port
Open

james-elicx wants to merge 9 commits into
fix/image-loader-configfrom
fix/legacy-image-port

Conversation

@james-elicx

@james-elicx james-elicx commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Stacked on #4905 (images.loader / loaderFile and custom-loader srcSets).

Problem

vinext's next/legacy/image wrapped the modern next/image shim and translated layout into styles. It did not render what Next.js's legacy component (packages/next/src/client/legacy/image.tsx) renders, so these Next.js v16.4.6 deploy-suite tests failed (run 45649241516):

  • No wrapper <span> or sizer per layout: the img got max-width/height:auto styles instead of Next.js's absolutely positioned img in a sized wrapper ("should handle the styles prop appropriately", "should correctly rotate image").
  • No IntersectionObserver lazy loading: lazy images got native loading="lazy" and their real src on the server, and lazyRoot/lazyBoundary were ignored ("should initially load only two of four images using lazyroot", "should re-lazyload images after src changes", unoptimized "should not optimize any image").
  • No <noscript> fallback, and Next.js's blur placeholder style was missing (sanitized away) ("should have blurry placeholder when enabled", "should not use blurry placeholder for image", "should remove blurry placeholder after image loads").
  • A user-provided srcSet reached the img; Next.js drops it ("should not pass through user-provided srcset").
  • Priority preloads and onLoad/onLoadingComplete timing differed ("should preload priority images", "should callback native onLoad in most cases").

Fix

shims/legacy-image.tsx is now a port of Next.js's legacy component: the same wrapper/sizer markup and styles per layout, getWidths/generateImgAttrs, handleLoading, the blur placeholder, <noscript>, Next.js's useIntersection (one shared observer per root and margin, requestIdleCallback fallback), re-lazy-loading on src change, and the dev-only checks and warnings. It keeps vinext's shim structure:

Deliberate differences, documented in the module header:

  • vinext's /_next/image serves only local images, so a remote src allowed by remotePatterns/domains loads directly, as with vinext's next/image. Any other remote src keeps Next.js's optimizer URL, which the endpoint rejects, as Next.js does for an unconfigured host. (Next.js would proxy allowed remote images through its optimizer; vinext's endpoint can't.)
  • vinext generates no blurDataURL for static imports, so a static import with placeholder="blur" renders no placeholder and no dev error, instead of url("undefined").
  • React ≥ 19.3 always has ReactDOM.preload, so Next.js's <Head> preload fallback for old React is left out. As in Next.js, React's server renderer preloads non-lazy images.

The LegacyBaseImage/legacyLayout hooks #4905 added to the modern shim are removed, since the port does its own srcSet widths.

Tests

  • tests/legacy-image-layout.test.ts: server-rendered markup ported from test/e2e/next-image-legacy/default: wrapper/sizer per layout, the exact style-prop strings, lazy placeholder + <noscript>, dropped srcSet, blur style (and none on the noscript copy), srcSet widths, remote sources. 12 of its 16 original cases fail on the base branch.
  • tests/e2e/pages-router-prod/legacy-image-lazy.spec.ts on a new pages-basic page, against the production server (ported from Next.js's lazy-withref, lazy-src-change, blurry-placeholder pages): lazyRoot/lazyBoundary, re-lazy-loading on src change, the SSR placeholder and <noscript>, blur cleared on load. 3 of 4 fail on the base branch. The spec runs in production because in the pages-router dev job the shims' ipaddr.js import gets a stale optimizer hash (504 Outdated Optimize Dep), so image pages never hydrate there. That predates this PR, which already imported it through image.tsx.
  • Blur url() breakout guard and dev remote hosts with no images config, in tests/legacy-image-layout.test.ts.
  • Updated the legacy assertions in image-data-blob-src, shims and the image-loader-file fixture (its legacy image is now priority so its URLs render on the server).

Ran: vp check on the changed files; vp test run tests/legacy-image-layout.test.ts tests/image-data-blob-src.test.ts tests/image-component.test.ts tests/image-loader-file.test.ts, vp test run tests/shims.test.ts -t legacy; PLAYWRIGHT_PROJECT=pages-router vp exec playwright test tests/e2e/pages-router/legacy-image-layout.spec.ts; PLAYWRIGHT_PROJECT=pages-router-prod vp exec playwright test tests/e2e/pages-router-prod/legacy-image-lazy.spec.ts.

Next.js deploy suite (v16.4.6, local run, --retries 0)

Baseline = #4905's head (matches the CI failures, minus the one #4905 fixed).

Test file Baseline failing This PR failing fail→pass pass→fail
next-image-legacy/default/default.test.ts 11 / 28 1 / 28 10 0
next-image-legacy/unoptimized/unoptimized.test.ts 1 / 1 0 / 1 1 0
next-image-legacy/unicode/unicode.test.ts 2 / 5 2 / 5 0 0
next-image-legacy/asset-prefix/asset-prefix.test.ts 1 / 2 1 / 2 0 0
next-image-legacy/image-from-node-modules/…test.ts 1 / 1 1 / 1 0 0
app-dir/next-image/next-image.test.ts (has legacy routes) 0 0 0 0

v16.2.6 has no next-image-legacy suites; app-dir/next-image/next-image.test.ts (legacy routes included) passes there too.

Known limitations

  • default "should callback onLoadingComplete when image is fully loaded" expects the optimizer to resize /test.jpg to 128px; vinext serves images as-is without an optimizer.
  • unicode external images: vinext's /_next/image doesn't fetch remote images.
  • asset-prefix blur: vinext generates no blurDataURL for static imports (next-image-new/asset-prefix fails the same way).
  • image-from-node-modules: a CommonJS package in node_modules requiring next/legacy/image 500s (next-image-new/image-from-node-modules fails the same way).
  • next-image-legacy-src-with-query-without-local-patterns (and its app-dir and non-legacy twins): needs the default loader's query-string localPatterns error and a failing build on a prerender render error; both are outside this port.
  • images.loader "imgix" / "cloudinary" / "akamai" still use the default loader (no images.path).

@james-elicx
james-elicx added this pull request to stack #4915 November 26, 2026 06:52
@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@4914

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@4914

@vinext/types

npm i https://pkg.pr.new/@vinext/types@4914

vinext

npm i https://pkg.pr.new/vinext@4914

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@4914

commit: 757b99a

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 13cc03364decf220af3f9c0c4c8a73fa9e094188 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread tests/legacy-image-layout.test.ts Fixed
@github-actions

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared 757b99a against base 2c78428 using alternating same-runner rounds. Next.js was unchanged and skipped.

1 improved · 0 regressed · 6 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 157.3 KB 157.3 KB ⚫ 0.0%
Client entry size (gzip) vinext 145.5 KB 145.5 KB ⚫ 0.0%
Dev server cold start vinext 2.97 s 2.90 s 🟢 -2.1%
Dev server cold start (large Pages Router app) vinext 25.69 s 25.86 s ⚫ +0.7%
Production build time vinext 3.87 s 3.84 s ⚫ -0.6%
RSC entry closure size (gzip) vinext 150.6 KB 150.6 KB ⚫ +0.0%
Server bundle size (gzip) vinext 262.8 KB 262.8 KB ⚫ +0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

backgroundSize: objectFit || "cover",
backgroundPosition: objectPosition || "0% 0%",
filter: "blur(20px)",
backgroundImage: `url("${blurDataURL}")`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: Sanitize blurDataURL before interpolating it here. This port bypasses sanitizeBlurDataURL(), which the previous legacy path inherited from image.tsx and which the modern component still uses. A value such as data:image/png;base64,x");color:red;background-image:url(" closes the quoted url() and injects additional CSS declarations after the HTML attribute is decoded. Please apply the shared sanitizer and omit the placeholder when it rejects the value.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1db0513. The legacy component now omits the blur placeholder when blurDataURL contains ", \ or a line break, the only characters that can end the quoted url("..."). Your payload now renders no placeholder, and there's a regression test in tests/legacy-image-layout.test.ts.

I didn't reuse sanitizeBlurDataURL() because it also rejects ', ( and ). Next.js's own legacy fixture uses them (test/e2e/next-image-legacy/default/pages/blurry-placeholder.js, url(%23blur) with single-quoted SVG attributes), and default.test.ts "should have blurry placeholder when enabled" asserts the exact background-image:url("...") output. The shared sanitizer would drop those placeholders and fail that test, which now passes.

);
}

if (!hasRemoteMatch(__imageDomains, __imageRemotePatterns, parsedSrc)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: This rejects every remote URL in development when neither images.remotePatterns nor images.domains is configured, because hasRemoteMatch([], [], ...) is always false. The same URL is explicitly allowed in production by validateRemoteUrl() (image-props.ts treats no image config as backwards-compatible allow-all), so apps now fail only in dev and regress from the previous legacy shim. Gate this check on configured patterns/domains or use the shared validation policy consistently.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1db0513. The dev host check now runs only when images.remotePatterns or images.domains is configured. This matches validateRemoteUrl(), which allows every host when neither is set. Added a regression test: in development with no remote config, a remote src loads directly. The configured-but-unmatched case still throws Next.js's error.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 actionable inline comments: 1 blocking, 1 warning.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head f40062fc855cfea1a6c7b7475041243dbd87a72c without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

// vinext allows every remote host when neither images.remotePatterns
// nor images.domains is configured (see validateRemoteUrl), so only
// reject an unmatched host once one of them is.
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning: Skip this configured-host validation when NODE_ENV === "test". Upstream Next.js explicitly gates hasRemoteMatch with process.env.NODE_ENV !== 'test', but isDev here includes test mode. As a result, component tests that render a remote image excluded by the configured patterns now throw during render; the previous legacy shim delegated to the modern shim, which only warned in this situation. Gate the hasRemoteMatch branch in test mode and add a test-mode regression case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 757b99a. The configured-host check now also requires process.env.NODE_ENV !== "test", matching upstream client/legacy/image.tsx. A regression test checks that an unmatched host doesn't throw under NODE_ENV=test. Development still throws Next.js's error.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 actionable inline comment: 1 warning.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 757b99ad13e6b386970e89654377e44e52cc1fb3 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

@james-elicx
james-elicx marked this pull request as ready for review November 26, 2026 07:35

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved — The next/legacy/image port has no outstanding findings. The blur placeholder guard, the dev remote-host check and the test-mode skip from earlier review rounds are all fixed and covered by tests.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

  • Blur placeholder: blurDataURL goes into url("...") only after isCssStringSafe rejects ", \ and line breaks, which blocks CSS breakout.
  • Remote sources: a remote src is returned directly only when validateRemoteUrl allows it, the same as the modern next/image shim.
  • Sizer SVG: the sizer data URL contains only the integers parsed from width and height.
  • Spread props: the user srcSet is dropped, and loader/layout are removed before ...rest is spread.

📖 AGENTS.md: ✅ LGTM

The change needs no AGENTS.md updates.


📋 Code Quality: ✅ LGTM

No callers of the removed LegacyBaseImage/legacyLayout hooks remain. resolveCustomImageLoader gets ignoreLoaderFile=true, so loaderFile is never read, as in Next.js's legacy component. The dev host check and validateRemoteUrl treat a missing images config the same way. The unit tests re-import modules after stubbing env, and the e2e spec matches the Playwright config and the fixture's assets.


⚡ Performance: ✅ LGTM

One IntersectionObserver is shared per root and margin, and it is cleaned up on unobserve. The image tracking and PerformanceObserver code runs only in dev. Module-level state matches upstream Next.js.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: 757b99ad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants