Repository navigation
[vite-plugin v1 backport] Support local image URL transformations #17315
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
NuroDev
merged 5 commits into
codex/vite-v1-runtime-20261129
from
codex/vite-v1-image-transforms-16678
Dec 3, 2026
+300
−13
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fbf8e1e
[vite-plugin v1 backport] Support local image URL transformations
petebacondarwin 88b0131
fix(vite-plugin): pass route hostname to image transformation router
dario-piotrowicz 3710536
address pr comments
dario-piotrowicz 657fbec
fix(vite-plugin): prefer `routes` over inherited `route` for image ro…
NuroDev 6ecb639
test(vite-plugin): resolve Windows short temp paths in image transfor…
NuroDev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| --- | ||
| "@cloudflare/vite-plugin": minor | ||
| --- | ||
|
|
||
| Add local development support for `/cdn-cgi/image/` URL transformations | ||
|
|
||
| Enable `images.url_transformations` in the Wrangler configuration to transform images locally, including files served by Vite from `public/` and through a parent server in middleware mode. Local transforms use the low-fidelity Sharp mock: resize, rotate, format conversion and a small set of options. Requests return 404 when transformations are disabled and 403 for disallowed origins, instead of reaching the Worker. | ||
|
|
||
| Same-host image sources are checked against `allowed_origins` using the hostname of the first configured route. Projects without a route continue to allow local sources. | ||
23 changes: 22 additions & 1 deletion
23
packages/vite-plugin-cloudflare/playground/static/__tests__/static.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,28 @@ | ||
| /// <reference lib="dom" /> | ||
|
|
||
| import { test } from "vitest"; | ||
| import { page } from "../../__test-utils__"; | ||
| import { page, viteTestUrl } from "../../__test-utils__"; | ||
|
|
||
| test("returns the correct home page", async ({ expect }) => { | ||
| const content = await page.textContent("h1"); | ||
| expect(content).toBe("Vite + TypeScript"); | ||
| }); | ||
|
|
||
| test("transforms images via /cdn-cgi/image/", async ({ expect }) => { | ||
| const response = await fetch( | ||
| `${viteTestUrl}/cdn-cgi/image/width=100,format=webp/image.png` | ||
| ); | ||
| expect(response.status).toBe(200); | ||
| expect(response.headers.get("content-type")).toBe("image/webp"); | ||
| expect(response.headers.get("cf-resized")).toBe("internal=ok/m"); | ||
| const bytes = Array.from(new Uint8Array(await response.arrayBuffer())); | ||
| const width = await page.evaluate(async (imageBytes) => { | ||
| const image = await createImageBitmap( | ||
| new Blob([new Uint8Array(imageBytes)]) | ||
| ); | ||
| const imageWidth = image.width; | ||
| image.close(); | ||
| return imageWidth; | ||
| }, bytes); | ||
| expect(width).toBe(100); | ||
| }); |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions
6
packages/vite-plugin-cloudflare/playground/static/wrangler.jsonc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "name": "static", | ||
| "compatibility_date": "2024-12-30", | ||
| "assets": {}, | ||
| "images": { "url_transformations": { "enabled": true } }, | ||
| } |
208 changes: 208 additions & 0 deletions
208
packages/vite-plugin-cloudflare/src/__tests__/image-url-transformations.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| import assert from "node:assert"; | ||
| import { once } from "node:events"; | ||
| import { readFileSync } from "node:fs"; | ||
| import { realpath } from "node:fs/promises"; | ||
| import { createServer as createHttpServer, get } from "node:http"; | ||
| import { createServer as createNetServer } from "node:net"; | ||
| import { buffer } from "node:stream/consumers"; | ||
| import { cloudflare } from "@cloudflare/vite-plugin"; | ||
| import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; | ||
| import { createServer } from "vite"; | ||
| import { afterEach, beforeEach, describe, test, vi } from "vitest"; | ||
| import type { RawConfig } from "@cloudflare/workers-utils/config"; | ||
| import type { IncomingMessage } from "node:http"; | ||
|
|
||
| const image = readFileSync( | ||
| new URL("../../playground/static/public/image.png", import.meta.url) | ||
| ); | ||
|
|
||
| const images = { | ||
| url_transformations: { | ||
| enabled: true, | ||
| allowed_origins: ["app.example.com/allowed"], | ||
| }, | ||
| }; | ||
|
|
||
| describe.each(["worker", "assets-only"] as const)( | ||
| "%s image URL transformations", | ||
| (type) => { | ||
| runInTempDir(); | ||
| afterEach(() => vi.unstubAllEnvs()); | ||
| beforeEach(async () => { | ||
| // Vite cannot load the Worker entry from Windows 8.3 short temp paths. | ||
| if (process.platform === "win32") { | ||
| const root = await realpath(process.cwd()); | ||
| process.chdir(root); | ||
| vi.stubEnv("PWD", root); | ||
| } | ||
| }); | ||
|
|
||
| async function createDevServer( | ||
| routeConfig: Pick<RawConfig, "env" | "route" | "routes"> = {}, | ||
| middlewareMode = false | ||
| ) { | ||
| await seed({ | ||
| "wrangler.json": JSON.stringify({ | ||
| name: "image-url-transformations", | ||
| ...(type === "worker" && { main: "worker.js" }), | ||
| compatibility_date: "2025-05-01", | ||
| assets: {}, | ||
| images, | ||
| ...routeConfig, | ||
| }), | ||
| "worker.js": `export default { | ||
| fetch() { return new Response("Worker fallback", { status: 418 }); } | ||
| };`, | ||
| "index.html": "<h1>Image URL transformations</h1>", | ||
| "public/allowed/image.png": image, | ||
| "public/blocked/image.png": image, | ||
| }); | ||
| // Miniflare needs the public URL's port before it starts in assets-only mode. | ||
| const portServer = createNetServer().listen(0, "127.0.0.1"); | ||
| await once(portServer, "listening"); | ||
| const address = portServer.address(); | ||
| assert(address && typeof address === "object"); | ||
| const closed = once(portServer, "close"); | ||
| portServer.close(); | ||
| await closed; | ||
| return createServer({ | ||
| root: process.cwd(), | ||
| configFile: false, | ||
| logLevel: "silent", | ||
| server: { | ||
| host: "127.0.0.1", | ||
| port: address.port, | ||
| strictPort: true, | ||
| middlewareMode, | ||
| }, | ||
| plugins: [ | ||
| cloudflare({ | ||
| inspectorPort: false, | ||
| persistState: false, | ||
| remoteBindings: false, | ||
| }), | ||
| ], | ||
| }); | ||
| } | ||
|
|
||
| test.for([ | ||
| { | ||
| name: "a route string", | ||
| routeConfig: { route: "app.example.com/*" }, | ||
| }, | ||
| { | ||
| name: "the first route object", | ||
| routeConfig: { | ||
| routes: [ | ||
| { pattern: "app.example.com/*", zone_name: "example.com" }, | ||
| { pattern: "other.example.com/*", zone_name: "example.com" }, | ||
| ], | ||
| }, | ||
| }, | ||
| { | ||
| name: "an environment's routes over an inherited route", | ||
| routeConfig: { | ||
| route: "other.example.com/*", | ||
| env: { staging: { images, routes: ["app.example.com/*"] } }, | ||
| }, | ||
| cloudflareEnv: "staging", | ||
| }, | ||
| ])( | ||
| "checks local sources against allowed origins using $name", | ||
| async ({ cloudflareEnv, routeConfig }, { expect, onTestFinished }) => { | ||
| if (cloudflareEnv) { | ||
| vi.stubEnv("CLOUDFLARE_ENV", cloudflareEnv); | ||
| } | ||
| const server = await createDevServer(routeConfig); | ||
| onTestFinished(() => server.close()); | ||
| await server.listen(); | ||
| const url = server.resolvedUrls?.local[0]; | ||
| assert(url); | ||
|
|
||
| const allowed = await fetch( | ||
| new URL("/cdn-cgi/image/width=50/allowed/image.png", url) | ||
| ); | ||
| const allowedBody = await allowed.arrayBuffer(); | ||
| expect(allowed.status, new TextDecoder().decode(allowedBody)).toBe(200); | ||
| expect(allowed.headers.get("cf-resized")).toBe("internal=ok/m"); | ||
|
|
||
| const blocked = await fetch( | ||
| new URL("/cdn-cgi/image/width=50/blocked/image.png", url) | ||
| ); | ||
| const body = await blocked.text(); | ||
| expect(blocked.status).toBe(403); | ||
| expect(body).toContain("ERROR 9401"); | ||
| } | ||
| ); | ||
|
|
||
| test("allows local sources when no route is configured", async ({ | ||
| expect, | ||
| onTestFinished, | ||
| }) => { | ||
| const server = await createDevServer(); | ||
| onTestFinished(() => server.close()); | ||
| await server.listen(); | ||
| const url = server.resolvedUrls?.local[0]; | ||
| assert(url); | ||
|
|
||
| const response = await fetch( | ||
| new URL("/cdn-cgi/image/width=50/blocked/image.png", url) | ||
| ); | ||
| const body = await response.arrayBuffer(); | ||
| expect(response.status, new TextDecoder().decode(body)).toBe(200); | ||
| expect(response.headers.get("cf-resized")).toBe("internal=ok/m"); | ||
| }); | ||
|
|
||
| test("fetches middleware image sources from the parent listener regardless of request headers", async ({ | ||
| expect, | ||
| onTestFinished, | ||
| }) => { | ||
| const vite = await createDevServer({ route: "app.example.com/*" }, true); | ||
| onTestFinished(() => vite.close()); | ||
| let wrongServerRequests = 0; | ||
| const wrongServer = createHttpServer((_req, res) => { | ||
| wrongServerRequests++; | ||
| res.writeHead(418).end("Wrong image source server"); | ||
| }).listen(vite.config.server.port, "127.0.0.1"); | ||
| onTestFinished( | ||
| () => new Promise<void>((resolve) => wrongServer.close(() => resolve())) | ||
| ); | ||
| await once(wrongServer, "listening"); | ||
| const parent = createHttpServer(vite.middlewares).listen(0, "127.0.0.1"); | ||
| onTestFinished( | ||
| () => new Promise<void>((resolve) => parent.close(() => resolve())) | ||
| ); | ||
| await once(parent, "listening"); | ||
| const address = parent.address(); | ||
| assert(address && typeof address === "object"); | ||
| expect(address.port).not.toBe(vite.config.server.port); | ||
| const url = `http://127.0.0.1:${address.port}`; | ||
| const source = await fetch(`${url}/allowed/image.png`); | ||
| expect(source.status).toBe(200); | ||
| expect(Buffer.from(await source.arrayBuffer())).toEqual(image); | ||
|
|
||
| for (const headers of [ | ||
| {}, | ||
| { | ||
| Host: `localhost:${vite.config.server.port}`, | ||
| "X-Forwarded-Host": `localhost:${vite.config.server.port}`, | ||
| "X-Forwarded-Proto": "https", | ||
| }, | ||
| ]) { | ||
| const response = await new Promise<IncomingMessage>( | ||
| (resolve, reject) => { | ||
| get( | ||
| `${url}/cdn-cgi/image/width=50/allowed/image.png`, | ||
| { headers }, | ||
| resolve | ||
| ).on("error", reject); | ||
| } | ||
| ); | ||
| const body = await buffer(response); | ||
| expect(response.statusCode, body.toString()).toBe(200); | ||
| expect(response.headers["cf-resized"]).toBe("internal=ok/m"); | ||
| } | ||
| expect(wrongServerRequests).toBe(0); | ||
| }); | ||
| } | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.