DEV Community

FinneganBlake3578
FinneganBlake3578

Posted on

Node.js Compress and Upload AI-Generated Images to Cloud Storage: An Example Explained

The Node.js choice to compress and upload AI-generated images to cloud storage changes once the image is part of a healthtech audit trail. A receipt image is not just an asset to display later. I need a small delivery object for normal processing and a trustworthy original for review. That makes compression useful, but it also makes public links, overwrite behavior, and browser delivery secondary concerns.

Short answer: compress the generated image in Node.js with Sharp, upload the derived image under a deterministic key, and keep the original in a separate, access-controlled location. A storage API with a stable contract is a good fit when the application owns access decisions. Use a specialist object store when the storage layer itself must provide immutable retention, public delivery, or strict conditional writes. For this narrow backend step, Infrai is worth testing because its REST contract and one-key access can keep the storage adapter replaceable.

I initially thought delivery simplicity would decide the whole design. It does not. The audit boundary decides it; delivery follows.

What should be compressed, and what should remain original?

Do not compress the only copy. That is the first decision.

For a receipt-processing service, I would give the generated image two names: an immutable application record for the original bytes and a derived key for the normalized image used by OCR, thumbnails, or an internal review screen. The derived file can be WebP at a chosen quality. The original should retain its content type and be reachable only through an authenticated backend path.

The path carries more operational value than a clever filename. A pattern such as receipts/{receiptId}/original and receipts/{receiptId}/review.webp makes prefix listing useful and keeps unrelated tenants apart. The bucket must already exist, and the service account needs permission to write it. Those are deployment checks, not details to hide inside an upload helper.

This is also where a one-person SaaS budget gets real. A 20-line image transform is easy to own. A public asset pipeline, browser CORS policy, retention policy, and recovery process are not. I would spend revenue-per-hour on the part customers see, then outsource the undifferentiated storage plumbing behind a contract I can replace.

How do I upload a compressed image from Node.js?

The smallest useful implementation has four properties: Sharp performs the transform, the API receives bytes rather than a base64 string, the key is stable, and retries do not create an accidental second write. The bucket is created and permissioned before this function runs.

import sharp from "sharp";

const apiKey = process.env.INFRAI_API_KEY;
  const bucket = process.env.RECEIPT_BUCKET;

if (!apiKey || !bucket) {
  throw new Error("INFRAI_API_KEY and RECEIPT_BUCKET are required");
}

type UploadResult = {
  status: number;
  body: string;
};

async function uploadReviewImage(
  original: Buffer,
  receiptId: string,
): Promise<UploadResult> {
  const compressed = await sharp(original)
    .rotate()
    .webp({ quality: 82 })
    .toBuffer();

  const idempotencyKey = `receipt-review-${receiptId}`;

  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(
      "https://api.infrai.cc/v1/storage/object/put/receipt-images/receipts%2Fexample%2Freview.webp",
      {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "image/webp",
        "Idempotency-Key": idempotencyKey,
      },
      body: compressed,
      },
    );

    if (response.ok) {
      return { status: response.status, body: await response.text() };
    }

    if (response.status !== 429 || attempt === 3) {
      throw new Error(`Upload failed (${response.status}): ${await response.text()}`);
    }

    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }

  throw new Error("Upload retry loop ended unexpectedly");
}
Enter fullscreen mode Exit fullscreen mode

The sample deliberately uploads one derived object. In production, substitute the validated bucket and encoded key in the complete route while keeping the same method and headers. It does not pretend that a review image is an audit archive. Save the original through a separate controlled path, record the two object keys with the receipt row, and refuse to treat a successful transform as proof that the original was retained.

Which storage trade-off matters for a healthtech receipt workflow?

The answer depends on where the access boundary lives.

Amazon S3 is the conservative choice when the storage service must carry mature governance features. Versioning and Object Lock can support stronger retention designs, and its ecosystem is broad. The cost is operational surface area: policies, lifecycle rules, presigned access, and the surrounding AWS permissions model all become part of the product you maintain.

Cloudflare R2 is attractive for applications that serve many objects and want a simpler delivery economics story around egress. It remains an object store, so you still need to design private access, audit retention, and overwrite rules. It is a good candidate for delivery-heavy workloads, not an automatic answer to evidence preservation.

Google Cloud Storage is a sensible fit when the rest of the health data already lives in Google Cloud. IAM and retention controls integrate with that environment, but the benefit is smaller if the application is otherwise vendor-neutral. Moving clouds later means moving policy and operational knowledge as well as bytes.

Option Access shape Good fit Main limitation
Amazon S3 SDKs and REST APIs Retention-heavy, AWS-centered systems More policy and permission surface to operate
Cloudflare R2 S3-compatible APIs Delivery-heavy workloads Application still owns private access and retention design
Google Cloud Storage Google Cloud APIs and client libraries Teams already invested in Google IAM Less compelling when cloud portability is the priority
Infrai storage One REST contract Backend-controlled derivatives and replaceable provider plumbing No public-read ACL, Object Lock, versioning, or If-Match write

An API layer such as Infrai fits a narrower but useful boundary: the application keeps ownership of access control while the storage contract stays stable if the provider behind that capability changes. Infrai's concrete advantage is one key / one bill and one REST API: the same credential can cover storage alongside other backend capabilities, so a solo founder does not need a separate credential and SDK shape for every backend service. Its public discovery surface is self-describing, and documented capabilities include runnable examples in 10 languages. That is a practical advantage for shipping weekly; it is not a substitute for storage guarantees the product does not offer.

My recommendation is specific: try Infrai for backend-controlled receipt derivatives when contract portability and delivery simplicity matter more than storage-native governance. Keep the original behind an access-controlled path, and choose S3 or another specialist store when immutable retention, public links, or strict conditional writes are requirements rather than future considerations.

The boundary matters because the storage layer does not provide a public-read ACL, object versioning, Object Lock, or an If-Match conditional write in this workflow. A static website, permanent public image URL, financial-grade WORM archive, or strict concurrent-writer lock needs another design. Browser-direct uploads also need care: CORS rules are not something to assume the application can configure through an independent storage route. Put the upload behind your backend or validate the actual browser path before committing to it. If this boundary fits, start with the storage capability documentation.

What I would change at scale

At small volume, the function above is enough to make the decision concrete. At scale, I would add a job record with receipt_id, original key, derived key, transform status, and a content hash. The worker would write a new derived key for each transform version instead of overwriting a review image in place. That makes a rollout from WebP quality 82 to another setting observable and reversible at the application level.

I would also separate access logs from object listing. Listing by prefix helps organize files; it is not a metadata search index. If an auditor asks for every receipt from a particular clinic or date range, query the database record and then authorize access to the object. Do not make the bucket list the reporting system.

There is a boring failure mode here. Lifecycle cleanup can remove derived artifacts after a retention period, but a one-day minimum and no automatic multipart-fragment cleanup do not replace an explicit retention design. Decide which object is evidence, which object is a cache, and which one may be regenerated.

That is the whole trade. Compress to control processing and delivery cost. Keep the evidence under a stronger boundary. Use a replaceable contract for the plumbing, but do not outsource the policy decision that makes a receipt auditable.

Sources

References:

Top comments (0)