Repository navigation
fix(image): port Next.js's next/legacy/image component - #4914
james-elicx wants to merge 9 commits into
Conversation
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
|
/bigbonk review for issues |
|
Performance benchmarksCompared 1 improved · 0 regressed · 6 within ±1.5%
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}")`, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 2 findings. Posted 2 actionable inline comments: 1 blocking, 1 warning. |
|
/bigbonk review for issues |
| // 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 ( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 1 findings. Posted 1 actionable inline comment: 1 warning. |
|
/bigbonk review for issues |
|
LGTM! |
There was a problem hiding this comment.
✅ 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:
blurDataURLgoes intourl("...")only afterisCssStringSaferejects",\and line breaks, which blocks CSS breakout. - Remote sources: a remote
srcis returned directly only whenvalidateRemoteUrlallows it, the same as the modernnext/imageshim. - Sizer SVG: the sizer data URL contains only the integers parsed from
widthandheight. - Spread props: the user
srcSetis dropped, andloader/layoutare removed before...restis 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
Stacked on #4905 (
images.loader/loaderFileand custom-loader srcSets).Problem
vinext's
next/legacy/imagewrapped the modernnext/imageshim and translatedlayoutinto 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):<span>or sizer perlayout: the img gotmax-width/height:autostyles instead of Next.js's absolutely positioned img in a sized wrapper ("should handle the styles prop appropriately", "should correctly rotate image").loading="lazy"and their realsrcon the server, andlazyRoot/lazyBoundarywere ignored ("should initially load only two of four images using lazyroot", "should re-lazyload images after src changes",unoptimized"should not optimize any image").<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").srcSetreached the img; Next.js drops it ("should not pass through user-provided srcset").onLoad/onLoadingCompletetiming differed ("should preload priority images", "should callback native onLoad in most cases").Fix
shims/legacy-image.tsxis 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'suseIntersection(one shared observer per root and margin,requestIdleCallbackfallback), re-lazy-loading onsrcchange, and the dev-only checks and warnings. It keeps vinext's shim structure:image-props.ts), notImageConfigContext.imageOptimizationUrl(basePath, trailingSlash,dpl,images.qualities), andimages.loader: "custom"uses fix(image): honor images.loaderFile and build custom loader srcSets like Next.js #4905'sresolveCustomImageLoader(legacy never readsloaderFile).Deliberate differences, documented in the module header:
/_next/imageserves only local images, so a remote src allowed byremotePatterns/domainsloads directly, as with vinext'snext/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.)blurDataURLfor static imports, so a static import withplaceholder="blur"renders no placeholder and no dev error, instead ofurl("undefined").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/legacyLayouthooks #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 fromtest/e2e/next-image-legacy/default: wrapper/sizer per layout, the exact style-prop strings, lazy placeholder +<noscript>, droppedsrcSet, 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.tson a newpages-basicpage, against the production server (ported from Next.js'slazy-withref,lazy-src-change,blurry-placeholderpages):lazyRoot/lazyBoundary, re-lazy-loading onsrcchange, 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.jsimport gets a stale optimizer hash (504 Outdated Optimize Dep), so image pages never hydrate there. That predates this PR, which already imported it throughimage.tsx.url()breakout guard and dev remote hosts with noimagesconfig, intests/legacy-image-layout.test.ts.image-data-blob-src,shimsand theimage-loader-filefixture (its legacy image is nowpriorityso its URLs render on the server).Ran:
vp checkon 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).
next-image-legacy/default/default.test.tsnext-image-legacy/unoptimized/unoptimized.test.tsnext-image-legacy/unicode/unicode.test.tsnext-image-legacy/asset-prefix/asset-prefix.test.tsnext-image-legacy/image-from-node-modules/…test.tsapp-dir/next-image/next-image.test.ts(has legacy routes)v16.2.6 has no
next-image-legacysuites;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.jpgto 128px; vinext serves images as-is without an optimizer.unicodeexternal images: vinext's/_next/imagedoesn't fetch remote images.asset-prefixblur: vinext generates noblurDataURLfor static imports (next-image-new/asset-prefixfails the same way).image-from-node-modules: a CommonJS package innode_modulesrequiringnext/legacy/image500s (next-image-new/image-from-node-modulesfails 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-stringlocalPatternserror and a failing build on a prerender render error; both are outside this port.images.loader"imgix" / "cloudinary" / "akamai" still use the default loader (noimages.path).