Repository navigation
fix(image): fix custom-loader srcSet, support images.loaderFile - #3686
AhmedElBanna80 wants to merge 26 commits into
Conversation
…ages.loaderFile next/image had three related gaps against Next.js's documented behavior: - imageOptimizationUrl() always emitted `/_next/image?...`, ignoring `trailingSlash: true`. Next.js emits `/_next/image/?...` in that case. Both the App Router and legacy Image shims share this helper, so both were affected. - A custom `loader` prop was called once with the intrinsic width and a forced quality of 75, producing a single `src` with no `srcSet`. Next.js gives a custom loader the same per-breakpoint treatment as the built-in loader: both the 1x and 2x (or sizes-derived) candidate widths, and the `quality` prop passed through as given (including `undefined`, letting the loader apply its own default) rather than forced to 75. - `images.loaderFile` was parsed but never wired up anywhere, so it had no effect. It's now resolved via a `resolve.alias` entry (aliasing the bare specifier `vinext:image-loader-file` to the configured file, or to a no-op default when unset) that the Image shim imports unconditionally and falls back to when no per-image `loader` prop is given. Fixes two of next/image's existing unit tests that had encoded the old (incorrect) custom-loader behavior, and adds coverage for all three fixes.
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
Performance benchmarksCompared 1 improved · 1 regressed · 5 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
…eakpoint srcSet tests/shims.test.ts has its own, separate custom-loader coverage for next/image that duplicates (but doesn't share with) tests/image-component.test.ts — it still pinned the old single-width/quality-75 behavior this PR replaced. Bring it in line with the per-breakpoint treatment: src is the 2x candidate, srcSet carries both 1x and 2x, and quality passes through as given (undefined here, since neither test sets a quality prop).
…h Next.js rules - Import the loaderFile slot as vinext/shims/image-loader-file so unit tests resolve it through the existing vinext/shims alias; drop the root vite.config.ts alias, the ambient .d.ts and the check-shim-types hook. - Keep that specifier bare in dist so the plugin alias still applies. - Apply loaderFile when images.loader is unset, default or custom, and throw Next.js's errors for other loaders or a missing file. - Skip remotePatterns validation in getImageProps when a custom loader owns the URL, as the component path and Next.js do. - Add dev-server fixture tests for trailingSlash, loader-prop srcSet and images.loaderFile.
|
Maintainer update (pushed
|
|
/bigbonk review for issues |
|
error: Your local changes to the following files would be overwritten by checkout: |
|
@james-elicx Bonk workflow timed out. View workflow run · To retry, trigger Bonk again. |
|
/bigbonk review for issues |
|
error: Your local changes to the following files would be overwritten by checkout: |
|
/bigbonk review for issues |
|
Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" to set your account's default identity. fatal: empty ident name (for runner@runnervm8df0l.3drbd0fvkhmelegyphvzhhcaub.bx.internal.cloudapp.net) not allowed |
… and custom mode - Give width-less (fill) images every device width and sizes=100vw when a custom loader or loaderFile is in effect, as Next.js getWidths() does. - Apply overrideSrc over the loader-generated src in both Image and getImageProps. - Throw Next.js's missing-loader error when images.loader is "custom" and an image has neither a loader prop nor a loaderFile, and its missing default export error for an empty loaderFile.
|
Bonk round 1 addressed in
All the new tests fail on the previous head and pass now. |
|
/bigbonk review for issues |
|
Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" to set your account's default identity. fatal: empty ident name (for runner@runnervm8df0l.ylsntxfoq4iuxizsmqxnehi3ne.dx.internal.cloudapp.net) not allowed |
… srcSet - Treat data: and blob: sources as unoptimized when a custom loader or loaderFile is in effect, as Next.js does, so the loader never sees them. - Order src after srcSet/sizes in the custom-loader <img> and in the getImageProps() result, matching Next.js's Safari-motivated prop order.
|
Bonk round 2 addressed in
|
|
/bigbonk review for issues |
|
Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" to set your account's default identity. fatal: empty ident name (for runner@runnervm8df0l.sgyfafs2kbnexlihx1gfup2jfd.cx.internal.cloudapp.net) not allowed |
…image - Join images.loaderFile onto the project root like Next.js, so a leading slash stays project-relative instead of pointing at the filesystem root. - Import the loader file as a namespace so a file without a default export reaches Next.js's missing-default-export error instead of failing to link (the browser) or to bundle (rolldown). - Keep next/legacy/image on its built-in loader: it never reads loaderFile, and its custom-mode error only fires for optimized images, as in Next.js.
|
Bonk round 3 addressed in
|
|
/bigbonk review for issues |
|
Author identity unknown *** Please tell me who you are. Run git config --global user.email "you@example.com" to set your account's default identity. fatal: empty ident name (for runner@runnervm8df0l.ybwjd3tuk2wenjvznezyc2abqa.jx.internal.cloudapp.net) not allowed |
… images Next.js applies fetchPriority, data-nimg and the blur placeholder background independently of which loader produced the URL; the custom-loader branch (loader prop or images.loaderFile) dropped all three.
|
Review: 2 findings. Posted both findings inline. |
…mage Next.js's getImgProps and next/legacy/image mark these sources unoptimized before building any URL. vinext only did that when a custom loader was present, so next/legacy/image under images.loader: "custom" (and the built-in loader generally) emitted /_next/image?url=data%3A... instead. Also make the static-export image spec fail on any console or page error, so production's minified hydration errors are caught.
|
Addressed both bonk findings in 9445847:
|
|
/bigbonk review for issues |
|
LGTM! |
Legacy responsive images get every device width with w descriptors and sizes=100vw, and fixed/intrinsic images keep 1x/2x candidates even when given sizes, matching getWidths() in Next.js's client/legacy/image.tsx.
…railing-slash-srcset # Conflicts: # pnpm-lock.yaml
…railing-slash-srcset # Conflicts: # packages/vinext/src/shims/image.tsx
# Conflicts: # pnpm-lock.yaml
|
This pull request was not reviewed automatically because its author does not have write access to this repository. A maintainer with write access can start a review by commenting |
Sem issue: requer o rótulo `no-issue`. Sucede #50. ## O quê - `src/components/ui/image.tsx` é o único ponto de importação de `next/image` no app. No `next build` ele só reexporta `next/image`, que já respeita `images.loaderFile` e monta o srcset. - `vite.vinext.config.ts` deixa de criar alias para `next/image` e troca `@/components/ui/image` por `web-worker/image.tsx`, que agora importa `next/image` normalmente. O módulo exporta nomes explícitos em vez de `export *`, porque o `@vitejs/plugin-rsc` não lê do disco o módulo virtual `next/image` do vinext para expandir um `export *` com `"use client"`. - Os seis componentes que usavam `next/image` passam a importar o módulo do app. Uma regra `no-restricted-imports` barra `next/image` em `src/` e `web-worker/` fora dos dois módulos. - As regras do Playwright foram, sem mudança, para `eslint.playwright.mjs`, porque `eslint.config.mjs` já estava no limite de 300 linhas do `max-lines`. - `vinext` ^1.3.0 e `@vinext/cloudflare` ^1.2.0 (exatos em `apps/web-workers`), com lockfile pelo `npm install`. O hold do Dependabot sai. - `@expires 2026-12-24` no wrapper: apagar quando o vinext respeitar `images.loaderFile` e o srcset de loader customizado (cloudflare/vinext#3686). ## Por quê Desde cloudflare/vinext#4055 (1.3.0), fora do ambiente `rsc` o vinext resolve `vinext/shims/image` via `this.resolve("next/image")`. Com o nosso alias global de `next/image`, o wrapper importava a si mesmo e `<Image>` renderizava `<Image>` sem fim. O Worker web estourava memória e CPU em toda página, e o `www` ficou em 502 até a #50 voltar o vinext para 1.0.1. Reportado em cloudflare/vinext#4262. Sem o alias de `next/image`, o vinext resolve o próprio shim como foi projetado. ## Verificação - Bundle de produção do vinext no commit final (`CLOUDFLARE_ENV=production … vite build --config vite.vinext.config.ts` + `wrangler dev -c dist/server/wrangler.json --local`): `/` 200 em 0,66 s, `/termos-e-condicoes` 200 em 0,09 s e `/noticias` 200 em 0,04 s, todos com `</html>`. No chunk SSR, o wrapper renderiza o shim do vinext, não a si mesmo. - E2E com `E2E_RENDERER=vinext` e com o renderer Next, 5/5 em cada: `ads/ad-with-photo`, `advertiser-profile/photo-upload`, `admin/blog`, `navigation/mobile-menu-navigation` e `legal/terms-navigation`. As rotas de foto de classificados devolvem 400 para larguras fora do conjunto configurado, então os dois primeiros cobrem o srcset do loader. - `npm run typecheck`, `typecheck:worker`, ESLint, `check:harness`, `lint:boundaries`, `build:check`, testes unitários dos componentes de imagem (28 arquivos, 107 testes), `vitest.worker.config.mts` (26 arquivos, 408 testes) e `git diff --check`. - A coleção E2E completa não foi rodada aqui. O deploy roda essa coleção, mas no renderer Next. --- _Generated by [Claude Code](https://claude.ai/code/session_01C2S56fDP1aqvpDKFZ41s2Q)_ <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touches production Cloudflare Worker rendering and responsive/classifieds image URLs; regression risk is mitigated by the alias change and targeted E2E, but deploy behavior still depends on vinext bundling. > > **Overview** > **Upgrades the Cloudflare web Worker stack to vinext 1.3.0 and @vinext/cloudflare 1.2.0**, lifting the Dependabot pins that blocked those versions after 1.3.0 caused production 502s from Worker memory/CPU exhaustion. > > The fix is an **app-level image facade** (`@/components/ui/image`): Next builds keep a thin re-export of `next/image`, while the vinext build aliases that module to `web-worker/image.tsx` instead of aliasing `next/image` globally. That avoids vinext 1.3+ resolving its shim back into the wrapper and infinite `<Image>` recursion. The worker wrapper still builds srcsets and honors custom loaders because vinext does not fully match Next’s `images.loaderFile` behavior. > > **Call sites** (ads, navigation, media, public/editorial images) now import the facade; ESLint **`no-restricted-imports`** enforces that in `src/` and `web-worker/`. Playwright ESLint blocks move unchanged into **`eslint.playwright.mjs`** so `eslint.config.mjs` stays under the line limit. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 011830e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-authored-by: Claude <noreply@anthropic.com>
The trailingSlash half of this PR is on main; next/image now applies images.loaderFile inside the shared shim (image.tsx / image-props.ts) instead of a separate entry, matching main's server-safe image split.
|
Merged current main and trimmed this PR. The trailingSlash half is on main, so it is gone from the description. The conflicts came from the server-safe image split: next/image no longer goes through a separate image-external entry. The loader file is now applied in the shared shim (image.tsx for the component, image-props.ts for getImageProps), which also keeps it working from Server Components, and the RSC next/image entry and the user-alias handling on main are untouched. One behaviour change: next/legacy/image still ignores the loader file, but the module is now evaluated on legacy-only pages too. The static-export e2e passes (3/3) and goes red for the loaderFile case if the fallback is removed; vp check and the image unit files pass. |
# Conflicts: # packages/vinext/src/index.ts
…iling-slash-srcset # Conflicts: # pnpm-lock.yaml
…ages.loaderFile Squashed from cloudflare#3686 (15 commits), rebased over the blur placeholder and remote-image changes. The static-export e2e fixture it adds is left out: it needs ipaddr.js as a fixture dependency, which would change the lockfile. Co-Authored-By: James <james@eli.cx> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
next/legacy/image again evaluated the images.loaderFile module on legacy-only pages: image-props.ts imported the loader-file slot, and legacy-image renders the shared component, which imports image-props. Next.js's client/legacy/image.tsx never imports the aliased image-loader module. - shims/image-loader.ts (new, server-safe) owns the loader-file import, withConfiguredLoader and next/image's getImageProps. - shims/image-base.tsx is the loader-agnostic component, moved from image.tsx. next/legacy/image renders it directly. - shims/image.tsx stays the next/image entry (same alias target): it wraps image-base with withConfiguredLoader. The RSC next/image entry takes getImageProps from image-loader. - image-props keeps buildImageProps (getImageProps without the loader file). Test: importing next/legacy/image does not evaluate the loader-file slot, and importing next/image does. It fails if legacy-image imports image.tsx.
|
@james-elicx Pushed
New unit test: importing next/legacy/image does not evaluate the loader-file slot, and importing next/image does. It fails if legacy-image imports Could you run |
What
Two gaps in
next/imagecompared with Next.js (a third,trailingSlashfor the built-in loader, is now onmainand was removed from this PR):A custom
loaderprop produced nosrcSetand forcedqualityto 75. The component andgetImageProps()called the loader once, with the intrinsic width (or0forfill) andquality ?? 75. Next.js runs a custom loader through the samegenerateImgAttrsas the built-in loader. That means 1x/2x widths,sizes-derived widths, or every device size plussizes="100vw"forfill, andqualitypassed through as given (includingundefined). Other loader-path details now also followgetImgProps:overrideSrcreplacessrcbut keeps the loader'ssrcSet.data:andblob:sources are unoptimized, so they never reach a loader or/_next/image. This applies to the built-in loader and next/legacy/image too.srcSetis dropped.srccomes aftersrcSet/sizes.priority,data-nimgand blur handling as the other paths.images.loaderFilehad no effect.next/image(the component andgetImageProps()) now falls back to the user's loader file when noloaderprop is given. The plugin aliases the slotvinext/shims/image-loader-file, which exportsundefinedby default, to the user's file, the same way Next.js aliasesnext/dist/shared/lib/image-loader. The rules are ported from Next.js'sserver/config.tsandgetImgProps:loaderFileapplies whenimages.loaderis unset,"default"or"custom". The path ispath.joined onto the project root.imgix/cloudinary/akamaithrows, and so does a missing file. Both use Next.js's messages.images.loaderFile detected but the file is missing default export.images.loader: "custom"with noloaderFilethrowsImage with src "..." is missing "loader" prop.for images that have noloaderprop.next/legacy/imagedoes not use the loader file, as in Next.js. Withloader: "custom"it throws only for optimized images.The loader file is applied inside the shared shim (
image-props.tsforgetImageProps(),image.tsxfor the component), on top of the server-safe split thatmainnow has, so it also works from Server Components. One difference from Next.js: the loader file module is imported byimage-props.ts, so a legacy-only page evaluates it too, even thoughnext/legacy/imagenever calls it.Testing
tests/e2e/static-export/images.spec.ts(Playwright,static-exportproject) runs against the checked-intests/fixtures/static-exportfixture. The fixture setsimages.loaderFile, which is Next.js's documented next/image setup foroutput: "export". Its/images/page renders next/image with the loader file (fixed size,fillandoverrideSrc), next/image with aloaderprop, and next/legacy/image on the built-in loader. The spec checkssrc,srcsetandsizesin the browser after hydration, and ports cases from Next.js'snext-image-new/loader-configtests. On the current head all 3 pass; with the loader-file fallback removed fromwithConfiguredLoader, the loader-file case fails. The fixture listsipaddr.jsbecause pnpm doesn't hoist vinext's copy.tests/image-loader-file.test.tscovers the config hook's alias and validation.tests/image-component.test.tsandtests/shims.test.tscover the shim behaviour. Two existing assertions that encoded the old single-width, quality-75 loader output were updated.main:vp check,sync-next-types --checkandcheck-shim-typesare clean, and the image, shim, alias and trailing-slash unit files pass (1618 tests).Not changed
next/legacy/imagelayout semantics andimages.path/basePathfor the built-in loader are unchanged from main.