How to build a Cloudinary alternative
How to build a Cloudinary alternative with private originals, bounded image transforms, signed delivery, and a cache. Follow ordered prompts and failure checks.
How to build a Cloudinary alternative starts with an original image and a few predictable output sizes. We will build Pixpipe, the project on the Cloudinary catalog page. It accepts an image, keeps the original private, and produces a version your page can use.
Choose a narrow image policy first. Our sample app accepts JPEG, PNG, and WebP images, then produces a small set of WebP widths. These are design choices for this tutorial, not statements about Cloudinary’s supported formats. Video, animated images, SVG, AI tagging, and a digital asset management suite stay outside this build.
The TinyPNG guide is a better starting point when you only need local compression. Pixpipe is useful when your own application needs durable uploads and controlled delivery URLs.
How to build a Cloudinary alternative with named presets
Use Astro for the authenticated asset library, HTMX for upload results, and Alpine for local progress and preview state. D1 stores metadata and jobs. R2 stores original and derived objects privately. Run decoding and transformation in a service with a supported image library and enforceable resource limits.
A Worker can verify delivery signatures and serve authorized derivatives from R2. Do not assume a native image library runs inside a Worker. A small Node service with a compatible image processor is a reasonable first transformer. Keep the storage adapter and processing adapter separate so deployment choices remain explicit.
The catalog gives a basic upload-and-transform estimate, a middle version with crops and named presets, and a much larger media platform. We will use named presets early to bound the public input. Arbitrary transform strings would create far more combinations to validate and cache.
Define the resource policy
Pick maximum upload bytes, maximum decoded pixels, accepted types, permitted widths, output format, and processing deadline. Those values belong in versioned configuration. The UI should display the upload limit before selection and explain when a photo exceeds it.
Keep the original bytes unchanged. The derived copy can strip metadata and resize without altering the source. If you later change the transform algorithm, increment its version so old and new derivatives do not share a cache key.
| Object | Stored data | Public access |
|---|---|---|
| Asset row | Owner, dimensions, hash, processing state | Owner only |
| Original | Validated uploaded bytes | Private |
| Preset | Width, fit, output format, version | Selected by name |
| Derivative | Generated bytes and dimensions | Authorized delivery |
| Job | Asset, preset, attempts, lease | Worker only |
Step 1 Model upload and processing states
An asset begins pending, becomes ready after validation, or becomes rejected with an actionable reason. A derivative moves from queued to processing to ready or failed. Store those states independently. One failed large preset should not make a valid thumbnail disappear.
Use generated object keys rather than client filenames. Keep the display name as metadata. An upload named ../../logo.png should remain a harmless label, never a storage path. Tie every object and row to an authenticated owner.
Create Pixpipe with owners, assets, versioned presets, derivative records, and
processing jobs. Use generated object keys and preserve display filenames only
as metadata. Model pending, ready, rejected, and failed states explicitly. Add
migrations and fixtures for an empty library, a ready image, and a failed job.
Every asset route and upload action must check ownership on the server.
Check the empty library and create an asset with a path-like filename. Confirm the storage key is generated. Attempt to load its detail page under another owner. The result should reveal no filename, dimensions, object key, or signed URL.
Step 2 Validate uploads before processing
A filename extension and browser MIME type are hints. Decode using a maintained library and verify the actual format. Enforce the byte cap while receiving the request, then enforce decoded dimension and pixel caps before expensive processing. Reject unsupported formats with a clear message.
Store a pending object privately while validation runs. If validation fails, delete the pending bytes and keep a minimal rejection record where useful. Clean up abandoned pending uploads with an age policy. An interrupted browser session should not accumulate permanent orphan objects.
Implement authenticated bounded uploads. Stream with a byte cap, detect format
from the bytes, and validate decoding plus maximum dimensions and decoded pixels.
Reject unsupported or animated inputs under this v1 policy. Keep pending objects
private. Finalize the asset row only after successful validation. Clean up failed
and abandoned uploads. Never trust the submitted filename or Content-Type.
Upload a valid small PNG, a text file renamed as PNG, a truncated JPEG, and an image that exceeds your configured pixel cap. Only the valid image becomes ready. Check that failed attempts leave no readable object. Also cancel an upload and verify the cleanup policy handles the pending entry.
Step 3 Generate one deterministic derivative
Begin with a thumbnail preset. Its normalized definition includes width, fit behavior, output format, metadata stripping, quality, and transform version. Combine that definition with the original content hash to derive a deterministic cache key.
Preserve aspect ratio unless the named preset explicitly defines a crop. Handle orientation before discarding metadata, or a portrait photo can rotate incorrectly. Avoid enlarging small inputs by default. Show the actual output dimensions in the asset detail page.
Add an image processor adapter for one named thumbnail preset. Normalize image
orientation, resize within the configured bounds without enlargement, strip
metadata, and encode WebP. Build a deterministic key from original content hash
and complete versioned preset. Write output to a temporary object, then publish
the derivative record only after success. Never replace the original bytes.
Use a portrait fixture with orientation metadata and a small square fixture. Verify the portrait stays upright and the square does not grow. Re-run the same job; the result should point to the same derivative identity. Change the preset version and verify it produces a different identity.
Inspect the output rather than the thumbnail alone
Download the output and inspect dimensions, format, and metadata with an independent image tool. A browser can hide orientation mistakes and show cached bytes. Use a fresh output key during this check. Include a transparent PNG fixture and define whether WebP preserves its transparency.
The Sharp resize documentation explains the resize options when Sharp is your chosen processor. Read the installed version’s metadata behavior before assuming the output is scrubbed. Your acceptance check should inspect the resulting file.
Step 4 Bound and deduplicate background work
A public URL should never start unlimited image processing. Create jobs only for allowed preset names and valid ready assets. Give each asset-and-preset-version pair a unique job identity. Use leases so a crashed worker can release work after a deadline.
Apply per-owner queue limits and a global processing concurrency cap. Retry temporary storage or worker failures with backoff. Reject invalid images permanently. A malformed input that exhausts retries on every request can keep your processor busy forever.
Implement a durable derivative queue with uniqueness on asset and preset version,
expiring worker leases, bounded retries, and explicit permanent failures. Enforce
per-owner job limits and global concurrency. Repeat requests reuse existing jobs.
Keep image decoding inside a process with memory and time limits. Expose failed
jobs and allow an authenticated owner to request a deliberate retry.
Request the same thumbnail from two tabs at once. Expect one job and one derivative. Kill the worker after its lease starts, then restart it after expiry. The job should recover. Make a storage write fail and confirm the temporary output cannot appear as a ready derivative.
Step 5 Sign delivery and choose cache behavior
A delivery token covers the asset id, preset version, owner or access scope, and expiry. Sign a canonical representation. Verify the signature and deadline before returning bytes, including cache hits. Keep the signing secret on the server and rotate it through a versioned key identifier.
For this tutorial, derivatives remain private. Use private cache controls and prevent a shared CDN cache from returning one owner’s image to another user. A later public-assets feature needs a separate explicit access policy and immutable public URLs. Mixing these policies under one cache key is difficult to review.
Add signed derivative delivery with canonical claims, expiry, key version, and
constant-time signature comparison. Verify authorization before every response,
including cached derivatives. Use private cache controls for the private v1.
Reject unknown presets, altered claims, expired tokens, and unavailable assets.
Never expose the original bucket or accept remote source URLs.
Generate a valid URL, then change its preset and expiry without updating the signature. Both should fail. Open a valid URL, wait past expiry, and request it again in a fresh session. It must fail even though the derivative already exists. Confirm error responses disclose no original object key.
Step 6 Deploy and verify deletion
Provision separate test and production R2 buckets and D1 databases. Configure bindings and secrets with Wrangler. Deploy the web application and processor independently, then confirm both use the intended environment. Keep worker concurrency conservative until you have measured memory use with your largest permitted fixture.
Follow the current R2 documentation for private object access. Keep processing credentials scoped to the required bucket operations. Record upload limits, cleanup age, queue settings, and signing-key rotation in the README. Estimate storage, request, processing, and egress costs separately for your chosen hosts.
Delete an asset through the authenticated app. Hide it from delivery immediately, then remove its original and derivatives through a retryable cleanup job. Mark deletion complete only after object removal succeeds. Old tokens must fail as soon as the asset is marked deleted, even while cleanup retries.
Diagnose broken images and stuck jobs
A ready asset with no thumbnail suggests a queue or processor problem. A ready derivative with a denied delivery suggests authorization, expiry, or signing configuration. Show those distinctions in the owner interface while keeping public failures generic.
If every thumbnail looks blurry, compare actual output dimensions with CSS display size and device pixel ratio. Add a second named preset when justified, rather than accepting arbitrary widths. If storage grows unexpectedly, inspect abandoned uploads and obsolete preset versions before raising limits.
Restore a backup into a test environment and verify database rows still point to available private objects. Keep a manifest of objects and checksums because a metadata backup alone cannot recover image bytes. The file transfer guide covers a related private-object lifecycle. Return to the Cloudinary prompt when this bounded image path is working, and add crops or public delivery as separate changes.