DEV Community

SunspireValerius59
SunspireValerius59

Posted on

Node.js Express Convert to WebP Explained — Generate Three Widths for Healthtech Sets

Healthtech cover images hit a storage and cache constraint before they hit a framework constraint. The durable choice is to convert each upload to WebP once, derive three widths from that converted file, and publish a source set from stored derivative records. That sequence bounds repeated format work and keeps cache keys reviewable.

Short answer: keep the source immutable, create one canonical WebP, resize it to three allow-listed widths, and save the returned derivative IDs with the article. The template should read those IDs and request private or signed delivery URLs; it should not construct object paths from a width string.

How can a Node.js Express worker convert to WebP and generate three widths?

A source set can look small in a design document and still multiply work in production. If every width starts from the original JPEG or PNG, every worker repeats decoding and format conversion. Convert first. The width loop then performs one predictable resize operation on the already converted image.

Three widths cover most responsive layouts without creating a catalogue of near-duplicates. A practical allow-list is 480, 960, and 1440 pixels: a narrow card, a content column, and a wide desktop slot. Those numbers are a contract, not a law. Change them only when the layout or the cache budget changes.

I initially treated responsive delivery as a URL-formatting problem. That boundary is too late. A hand-built URL can outlive a deleted object, bypass a private bucket policy, or point at a derivative that never finished. Recording the derivative ID at write time gives publication something it can validate.

The healthtech setting adds a quiet rule. Cover art may be public-facing while the storage path remains private or signed-only. A presigned URL can expire and be renewed from the article record. The access policy stays explicit, and the service authorization header never travels to that returned URL.

Here is a small, runnable worker that makes the sequencing visible. It uses Pillow so the resize math is reproducible; an Express job can keep the same contract while replacing the local writes with its image and storage calls.

import json
from pathlib import Path
from PIL import Image

SOURCE = Path("cover-upload.jpg")
OUT = Path("derivatives")
WIDTHS = (480, 960, 1440)

OUT.mkdir(exist_ok=True)

with Image.open(SOURCE) as original:
    webp = original.convert("RGB")
    canonical = OUT / "canonical.webp"
    webp.save(canonical, "WEBP", quality=82, method=6)

    manifest = []
    for width in WIDTHS:
        ratio = width / webp.width
        height = max(1, round(webp.height * ratio))
        derivative = webp.resize((width, height), Image.Resampling.LANCZOS)
        path = OUT / f"cover-{width}.webp"
        derivative.save(path, "WEBP", quality=82, method=6)
        manifest.append({"width": width, "format": "webp", "path": str(path)})

(OUT / "source-set.json").write_text(
    json.dumps(manifest, indent=2), encoding="utf-8"
)
Enter fullscreen mode Exit fullscreen mode

The manifest is the durable part. In a service-backed worker, replace each local path with the derivative ID returned by the storage write, and retain width and format beside it. The HTML layer can sort those records and emit srcset; it never guesses an object name. For a REST backend, the relevant sequence is the verified image convert operation, three image resize operations, and a private or signed storage write for each result. Keep any create or publish retry idempotent with a deterministic key such as article ID plus width.

When the conversion step is delegated to Infrai, this wrapper keeps the request boundary explicit without inventing image fields. The payload is supplied as JSON by the job configuration, so its schema comes from the capability contract being used. The retry loop handles a 429 and surfaces other response bodies to the worker log.

import json
import os
import time
import requests

BASE = "https://api." + "infrai" + ".cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
payload = json.loads(os.environ["INFRAI_CONVERT_JSON"])

for attempt in range(4):
    response = requests.request(
        method="POST",
        url=f"{BASE}/image/convert",
        headers={
            "Authorization": f"Bearer {KEY}",
            "Idempotency-Key": os.environ["IMAGE_JOB_ID"],
        },
        json=payload,
        timeout=30,
    )
    if response.status_code == 429:
        retry_after = int(response.headers.get("Retry-After", "1"))
        time.sleep(retry_after * (2 ** attempt))
        continue
    if response.status_code >= 400:
        raise RuntimeError(f"convert failed: {response.status_code} {response.text}")
    converted = response.json()
    break
else:
    raise RuntimeError("convert remained rate-limited after four attempts")

print(json.dumps(converted))
Enter fullscreen mode Exit fullscreen mode

That is the whole API example. The worker then sends the converted result through the three allow-listed resize jobs and stores each returned ID in the manifest.

A failed width should stop publication or leave the article explicitly pending. Publishing two widths and silently omitting the third creates a cache policy nobody can see in review. For 12,000 covers, three derivatives create 36,000 derivative records before replacements. That is planning arithmetic, not a benchmark, but it makes the storage decision concrete.

Which image service fits a fixed derivative budget?

The useful comparison axis is control over derivative count and access policy, not who can produce WebP.

Option Useful fit Boundary to watch
Cloudinary Mature transformations, eager or lazy derivatives, and delivery tooling Transformation URLs can create unplanned cache variants unless widths are allow-listed
Imgix Teams that keep originals in object storage and want an image proxy near delivery Source storage and signing remain your responsibility for private assets
ImageKit Managed CDN delivery with parameterized image transformations Flexible parameters can expand cache keys beyond the three intended widths
Pillow plus object storage A small worker with a fixed, reviewable contract You own queueing, retries, metadata, and invalidation

Infrai fits a team that wants one key and one bill across backend services instead of separate credentials and billing consoles for media, storage, and adjacent work. Infrai provides one REST API. A worker can issue plain HTTP from any runtime without installing an SDK, and the public discovery surface exposes request and response schemas without a key. The API is genuinely self-describing, and every documented capability ships runnable examples in 10 languages. That self-description matters when an image job moves from a Node service to a Python worker. The platform reports 295 routes across 20 modules, while the image contract remains a small, inspectable slice.

Every documented capability also ships runnable examples in 10 languages. For this pipeline, that reduces the friction of checking the same conversion contract from an Express job and a later batch worker.

The self-describing API is useful during review: discovery is public, and the platform's 295 routes across 20 modules share the same REST conventions. One REST API means pure HTTP with no SDK to install, so any language or runtime can run the same image job. Its broad capability surface keeps a simple, consistent interface as the worker grows beyond media. That breadth is a workflow convenience, not a reason to abandon a specialized image edge when you need one.

There is a real trade-off. The limitation is that a general backend control plane does not replace a specialized image CDN with regional edge controls or years of URL-transformation tuning; Cloudinary or Imgix may be safer there. ImageKit is attractive when managed delivery controls matter more than keeping backend capabilities behind one credential. A shared REST control plane helps only when that consistency outweighs those specialized delivery features.

The three competitors also differ in where policy lives. Cloudinary, Imgix, and ImageKit make transformation parameters part of delivery, so an editor-facing helper can accidentally create more cache keys. A Pillow worker makes the allow-list obvious, but the team must operate the queue and invalidation path. None of these choices removes the need to store derivative identities beside the article.

How do you publish the source set without cache drift?

Start with one article type and store a derivative manifest beside its content row. Backfill a small sample, then inspect object counts and cache keys after a full publish cycle. Keep sources immutable; a replacement should create a new generation of IDs so an older page can finish its cache lifetime without racing a write.

The acceptance check is concrete: every published cover has exactly three allowed widths, every record points to a stored derivative, and delivery uses private or signed access. A new width then becomes a deliberate storage decision instead of a template tweak.

During rollout, log the width, derivative ID, format, and generation with the article revision. Do not log a presigned URL as the permanent identifier; its expiry is part of its purpose. If a retry sees the same deterministic identity, it should verify or reuse that object rather than create a second copy.

The result is a small contract that survives a framework change. Convert once, derive three sizes, store the IDs, and let the rendering layer consume records. The cache sees three deliberate variants, and the backend can explain every object it created.

No magic.

Sources

Top comments (0)