Efficient image hosting: CDNs & processing
Static delivery and image transformation solve different problems. A static CDN caches files that
already exist; it does not resize a JPEG simply because you append ?width=800. Here you will generate
versioned files from a trusted local photograph and open a responsive preview with a one-shot
image fallback. You can then publish those same files to your image hosting CDN.
Choose static files or dynamic transformations
Prebuilding avoids decoder work when a new image URL is requested. You store and publish a known set of files, including variants that might never be requested. A versioned URL identifies one file with fixed dimensions and format, which makes generation failures easier to distinguish from delivery failures.
Choose between prebuilt variants and a transformation service deliberately. If you need arbitrary resizing, use a processing origin or a service such as Transloadit's Smart CDN. Verify that service's parameter and signing contract; static S3/CloudFront objects do not interpret transformation query parameters.
Cloudinary
Hosted transformation services define their own URL grammar and allowed source locations. Follow Cloudinary's transformation reference or the equivalent documentation for your provider. A URL from one provider cannot be used as a generic resize contract on another CDN.
Tools and libraries for image processing
Sharp (Node.js)
Use a maintained Node.js 26 release and separately installed Corepack. This example was tested with Node.js 26.12.1 and 26.13.0, plus Yarn 4.12.0. Sharp 0.35.4 is the reproducibility pin here, rather than a claim that it is the newest patch. See Sharp's installation prerequisites for supported platforms and optional native packages.
Run this Bash block from a writable directory. It creates a separate Yarn project and leaves your shell in its original directory. The empty lockfile establishes a project boundary even inside an existing workspace; Yarn still reads applicable parent configuration.
(
command -v node >/dev/null &&
command -v corepack >/dev/null &&
mkdir image-publish &&
cd image-publish &&
printf '%s\n' '{"private":true,"packageManager":"yarn@4.12.0"}' > package.json &&
touch yarn.lock &&
corepack yarn add --exact sharp@0.35.4
)
If image-publish already exists, choose another new directory name instead of removing its contents.
If installation fails after creation, inspect that directory and choose a fresh name for the next
setup attempt. After a successful install, open a terminal in image-publish. Use corepack yarn node
for the script so both Yarn's default Plug’n’Play installation and its node-modules linker work.
Provide photo.jpg: its contents may be JPEG or PNG regardless of this fixed filename. Use a trusted
8-bit sRGB image without an alpha channel. The input must be nonempty and no larger than 8 MiB, with at most
12,000,000 pixels and at least 1280 pixels of width after EXIF orientation. It rejects other decoded
formats, color spaces and sample depths. This is a sequential publishing job, not an upload endpoint
or a general validator for hostile files. JPEG and PNG containers are read as a primary still; this does not
establish that an MPO companion, APNG animation or HDR gain map was processed.
Save this as build-images.mts:
import { mkdir, open, writeFile } from 'node:fs/promises'
import sharp, { type SharpOptions } from 'sharp'
async function main() {
const file = await open('photo.jpg', 'r')
let source
try {
const stat = await file.stat()
if (!stat.isFile() || stat.size < 1 || stat.size > 8 * 1024 * 1024) {
throw new Error('Use a regular source image no larger than 8 MiB.')
}
source = Buffer.alloc(stat.size)
let offset = 0
while (offset < source.length) {
const { bytesRead } = await file.read(source, offset, source.length - offset, null)
if (bytesRead === 0) throw new Error('Source changed during publishing.')
offset += bytesRead
}
} finally {
await file.close()
}
const options: SharpOptions = { limitInputPixels: 12_000_000, failOn: 'warning' }
const metadata = await sharp(source, options).metadata()
if (!['jpeg', 'png'].includes(metadata.format) || (metadata.pages ?? 1) !== 1) {
throw new Error('Use a JPEG or PNG primary image.')
}
if (metadata.space !== 'srgb' || metadata.depth !== 'uchar' || metadata.hasAlpha) {
throw new Error('Use an 8-bit sRGB image without an alpha channel.')
}
const orientedWidth = metadata.autoOrient?.width ?? metadata.width
if (!orientedWidth || orientedWidth < 1280) throw new Error('Source must be at least 1280px wide.')
await mkdir('images', { recursive: true })
for (const width of [320, 640, 1280]) {
const result = await sharp(source, options).rotate().resize({ width }).webp({ quality: 80 })
.toBuffer({ resolveWithObject: true })
await writeFile('images/photo-' + width + '-v1.webp', result.data, { flag: 'wx' })
}
const fallback = await sharp(source, options).rotate().resize({ width: 640 })
.jpeg({ quality: 80 }).toBuffer({ resolveWithObject: true })
await writeFile('images/photo-640-v1.jpg', fallback.data, { flag: 'wx' })
console.log(JSON.stringify({ width: fallback.info.width, height: fallback.info.height }))
}
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : 'Image publishing failed.')
process.exitCode = 1
})
Run the saved program from that directory:
corepack yarn node build-images.mts
It writes three width-only WebP variants, at 320, 640 and 1280 pixels, plus a 640-pixel JPEG fallback. All preserve the oriented aspect ratio. The final JSON line reports the JPEG's actual width and height. Open the local preview and inspect the image before uploading anything; quality 80 is an encoder setting, not a promise of a particular file size or perceptual quality.
Do not modify the input during a run. Exclusive writes refuse existing output filenames, including
the JPEG fallback. A failure can leave partial output; inspect it and use a fresh version for a
retry. Change v1 in every output name and HTML reference together when publishing a new version.
The job does not roll back files it has already written.
Sharp's automatic orientation applies the EXIF orientation before resizing. Its default output behavior removes source metadata. Inspect the rendered colors and orientation yourself; these bounds do not prove that a damaged original is intact.
ImageMagick
If you already have ImageMagick 7 with JPEG and WebP support, this Bash command creates one small WebP from the same approved source. It was tested with ImageMagick 7.1.2-32; obtain maintained updates from ImageMagick's downloads.
(
set -o noclobber
magick photo.jpg -auto-orient -resize '640x640>' -strip -quality 80 webp:- > photo-small.webp
)
The quoted resize geometry fits within
640 × 640 without enlargement. A 1280 × 720 image becomes 640 × 360; a 320 × 180 image stays that size.
This differs from the Sharp script's width-only variants and does not create the preview's full set.
The shell refuses an existing photo-small.webp before starting conversion. Failed conversion may
leave an empty or partial new file; inspect it before retrying with a fresh name. The command has
none of the Sharp script's input guards. Use only the already approved 8-bit sRGB source here;
untrusted files need process isolation and decoder/resource policies.
Preview responsive prebuilt images
Save this complete page as index.html beside the generated images/ directory. Save the error-handling block immediately below as fallback.js, then open index.html in your browser. Its relative paths work directly from the local directory.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive image preview</title>
<body style="margin: 0">
<picture>
<source
type="image/webp"
data-srcset="images/photo-320-v1.webp 320w, images/photo-640-v1.webp 640w, images/photo-1280-v1.webp 1280w"
sizes="(max-width: 640px) 100vw, 640px"
>
<img
id="hero"
data-src="images/photo-640-v1.jpg"
data-fallback="images/placeholder.png"
alt="A description of your photograph"
width="640"
height="360"
style="display: block; width: 100%; max-width: 640px; height: auto"
>
</picture>
<script src="fallback.js"></script>
</body>
</html>
Set width and height to the actual JPEG fallback dimensions printed by the script. The 640 × 360
values fit a 16:9 source; other aspect ratios need different heights. Replace the alt text with a
description of your image. The sizes value matches this page's layout, which stops growing at
640 CSS pixels. A browser can choose among the WebP candidates using its viewport and pixel density;
the JPEG is the default when WebP is not selected.
The data-src and data-srcset attributes delay requests until fallback.js installs its handler.
This preview needs JavaScript. Supply your own real PNG as images/placeholder.png, or use a copy of
an approved PNG. To try recovery, temporarily rename the selected WebP file and reload the page.
Restore it afterward. A missing placeholder should leave the image's alt text without repeated retries.
Image load error handling
Save this as fallback.js beside index.html. It registers the handler before activating the
preview URLs. Removing the responsive candidates lets the placeholder become the selected image:
function installImageFallback(image, fallbackUrl) {
image.addEventListener('error', () => {
for (const source of image.closest('picture')?.querySelectorAll('source') ?? []) {
source.remove()
}
image.removeAttribute('srcset')
image.removeAttribute('sizes')
image.src = fallbackUrl
}, { once: true })
}
const hero = document.getElementById('hero')
if (hero instanceof HTMLImageElement) {
installImageFallback(hero, hero.dataset.fallback ?? '/images/placeholder.png')
for (const source of hero.closest('picture')?.querySelectorAll('source') ?? []) {
if (source.dataset.srcset) source.srcset = source.dataset.srcset
}
if (hero.dataset.src) hero.src = hero.dataset.src
}
The handler runs once per image element. If the placeholder fails too, the browser retains the accessible alt text and no further fallback assignment occurs. In an existing application, attach the handler before setting image URLs so an immediate failure cannot arrive before registration.
Publish versioned files to your CDN
Upload the generated WebP files and JPEG fallback from images/, together with your placeholder, to an approved public-content prefix. Preserve the relative paths or replace every image URL in the preview with its CDN URL. Set image/webp, image/jpeg and image/png content types for their respective files. Do not upload private originals into that prefix.
Use long cache lifetimes for immutable, versioned objects. Set cache-control metadata intentionally, then inspect the CDN response headers; changing origin metadata does not instantly replace cached responses.
You do not need a cloud account for this local example. For infrastructure provisioning, see the separate S3 and CloudFront setup guide. It is further reading, not a prerequisite for the preview.
For that deployment, check the current AWS private-origin requirements. OAC uses a regular S3 bucket origin, not a website endpoint. With bucket-owner-enforced ownership, always-signed OAC requests and a distribution-scoped bucket policy, CloudFront can read a private origin. Objects encrypted with SSE-KMS also need the appropriate KMS key policy. Viewer HTTPS and viewer authorization are separate settings; OAC does not authenticate visitors to a public CDN URL.
Security considerations when using CDNs
Private origins and private delivery are separate controls. For private viewer access, configure CloudFront signed URLs and the associated trusted key group. An S3 presigned URL does not automatically sign CloudFront.
Keep signing keys server-side, authorize the requested object before issuing access and avoid logging signed query strings. Do not publish private responses with a shared public cache policy.
Troubleshoot common CDN image hosting challenges
Cache invalidation
Prefer a new immutable filename for a new image. When invalidation is necessary, target only the intended distribution and paths. An invalidation is a real account operation and may have a cost; do not run it as a generic debugging command against production.
Performance monitoring
Use the browser's network panel to inspect the selected image request, response size and cache headers. Test representative devices and cold as well as warm caches. The local preview verifies file selection and recovery; it does not measure a deployed CDN's latency or prove bandwidth savings.
Rather not run this yourself?
Transloadit’s Smart CDN transforms and delivers files on the fly.
