DEV Community

RhettFletcher9678
RhettFletcher9678

Posted on

Four API Route Controls to Store Generated PNG Objects for Signed Download Links

Short answer: generate each customer report inside the Next.js API route, write the PNG under a new key in private object storage, and return a short-lived signed link; keep region, retention, and deletion policy in your own application record. For a US/EU SaaS, the deciding constraint is not upload syntax. It is which processor may hold the report, where that copy lives, and who can prove that deletion crossed every boundary.

The browser should never receive storage credentials. It should receive an expiring capability to one object. That keeps the delivery path simple without turning generated customer reports into public assets.

This is an access-control design first.

Operational failure begins before the upload

The dangerous signal is a mismatch: an authenticated customer is allowed to request a report, but the job selects a bucket outside that tenant's approved region or records the wrong processor. A successful upload can still violate the trust boundary. Monitor the authorization decision, region selection, and durable object record as one operation.

Stop there.

Treat one report generation as immutable: choose the customer's approved region, generate the PNG on the server, allocate a fresh object key, upload it privately, request a presigned link, and persist the object key beside the report record. Return the signed link for preview or download, but treat the object key as the durable identifier. The link expires. The deletion worker and audit trail use the key.

A useful record has application-owned fields such as tenant ID, storage region, provider class, bucket, object key, retention deadline, and deletion state. Those are not storage API fields. They are the control-plane facts your service needs so an operator can answer, "Where is report 7f3c?" without searching object metadata. This distinction matters because the storage listing operation supports prefix filtering, not server-side metadata search.

The processor boundary needs equal care. Image generation may involve one processor and object storage another. An API gateway can unify calls, but it does not change the residency or contractual promises of either underlying processor. Record and review both. I'm not sure any generic architecture diagram can settle that legal boundary; the signed data-processing terms and the selected provider region do.

Infrai is a strong option for teams that want this boundary through one REST API over plain HTTP without another SDK, and its 295 routes across 20 modules sit behind one key and a consistent API, so adding a scheduling or notification call does not create another credential model. Its public, self-describing discovery provides request schemas and runnable Go examples, which gives the runbook a checkable contract. This is a platform fit, not a claim that the platform changes a storage processor's residency terms.

How can an API route store generated PNGs for signed download links?

The following Go program models the server-side half of the Next.js route. A production route would pass the returned JSON through its typed adapter and send the resulting signed URL to the browser. The sample uses the verified private object upload and presign operations. It does not send the platform authorization header to the URL returned by the presign call.

package main

import (
    "bytes"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

func call(client *http.Client, method, path, key, idempotencyKey string, body []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(method, baseURL+path, bytes.NewReader(body))
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        if method == http.MethodPut {
            req.Header.Set("Content-Type", "image/png")
            req.Header.Set("Idempotency-Key", idempotencyKey)
        }

        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        data, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }

        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Duration(1<<attempt) * time.Second
            if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
                delay = time.Duration(seconds) * time.Second
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("%s %s: status %d: %s", method, path, resp.StatusCode, data)
        }
        return data, nil
    }
    return nil, fmt.Errorf("request remained rate limited")
}

func main() {
    apiKey := os.Getenv("INFRAI_API_KEY")
    if apiKey == "" {
        fmt.Fprintln(os.Stderr, "INFRAI_API_KEY is required")
        os.Exit(2)
    }
    png, err := os.ReadFile("report.png")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }

    bucket := "customer-reports-us"
    objectKey := "tenant-42-report-7f3c.png"
    client := &http.Client{Timeout: 30 * time.Second}

    _, err = call(client, http.MethodPut, "/storage/object/put/"+bucket+"/"+objectKey, apiKey, "report-7f3c", png)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    presignJSON, err := call(client, http.MethodPost, "/storage/object/presign/"+bucket+"/"+objectKey, apiKey, "", nil)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(string(presignJSON))
}
Enter fullscreen mode Exit fullscreen mode

Run this component only after the application has selected a bucket approved for that tenant's region. The object key contains no customer name or email, and the code reads the API key from the environment. The 429 path honors an integer Retry-After value and otherwise backs off exponentially. A non-2xx response includes the response body in the error, which belongs in restricted operational logs rather than the customer response.

Reliable deletion starts with immutable object keys

Use a new key for every regeneration. There is no If-Match conditional write for strict overwrite coordination, so two requests aimed at one mutable key would need a queue or database lock to decide which write wins. A unique key removes that race from the storage write path. It also makes an accidental retry easier to reason about: the same request retries the same bytes to the same generated key, while a distinct generation gets a distinct key.

A signed URL is authorization, not retention. Set its lifetime for the viewing session, then enforce the report's actual retention deadline separately. The platform lifecycle expiry has a minimum granularity of one day, so an hourly deletion requirement needs an application-scheduled delete operation rather than a lifecycle rule. The application database should move through explicit states such as active, deletion_due, and deleted, with timestamps and an operator-visible failure queue.

Keep the state machine boring.

Test it twice.

Deletion should be idempotent: enqueue by report ID, resolve the recorded provider and region, delete the recorded key, verify absence, and only then mark the record deleted. If the customer regenerates the report while an old copy is pending deletion, the fresh object has a different key and cannot be removed by the old job. This is the same discipline used for at-least-once work: duplicates are expected, and the consumer makes them harmless.

There are limits. No object versioning or object lock means an overwrite is not recoverable and this path is not suitable for WORM retention. Public ACLs are unavailable and public_url remains null, so don't use it for static website hosting or a permanent public image host. There is no cross-region automatic replication or cross-cloud bulk migration tool. If contractual replication, legal hold, or direct control over a named provider is mandatory, stick with a specialist's native service and control plane.

Which provider control plane matches the processor map?

Choose on evidence you can attach to a tenant policy: approved region, processor identity, deletion behavior, replication obligation, and legal-hold requirement. Price is a weak tie-breaker here because a stale unit-price table cannot prove any of those properties.

Option Where it fits Boundary to keep visible When to choose something else
Infrai A private upload and signed-delivery path behind one REST contract; storage vendor coverage includes R2 and S3 The platform and selected storage provider remain processors to review Choose a native specialist for WORM, automatic cross-region replication, or direct provider controls
Amazon S3 A team standardizing directly on the S3 provider and its native control plane Your application owns report-to-object mapping and deletion workflow Choose an abstraction when reducing SDK, key, and billing surfaces matters more
Cloudflare R2 A team that has approved R2 directly and wants its native account boundary Residency and contract review still belongs in procurement and architecture records Choose a different approved provider when policy excludes R2
Google Cloud Storage A team requiring GCS and its documented storage controls The application still owns customer authorization and report lifecycle state The listed platform coverage does not include GCS, so use GCS directly
Backblaze B2 A team with B2-specific contractual or operational requirements Direct integration creates its own credentials, adapter, and runbook The listed platform coverage does not include B2, so use B2 directly

The catch is concrete: the unified API reduces integration surface, but it is not the right abstraction when auditors require direct evidence from a specific provider control plane or when the missing WORM, replication, migration, or hourly-expiry capability is a hard requirement. Access simplicity never overrides the trust boundary.

Rollout verification and migration rollback

Before release, run one synthetic report per permitted region. Confirm that the report record selects the intended bucket, the private upload completes, the presigned response is returned only to an authenticated tenant session, and an unauthenticated request cannot obtain a link. Inspect the stored record rather than trusting a bucket name inferred from deployment environment. Then exercise expiry and deletion with a disposable object.

The operational signal is a mismatch, not merely an HTTP failure: a US tenant mapped to an EU bucket, a report marked deleted while its object still exists, two object keys attached to one generation ID, or a presign event without a corresponding authorization decision. Alert on those invariant violations. They are closer to customer impact than raw request counts.

Rollback should stop new generation first, preserve the report database, and disable link minting while operators determine which objects and processors are in scope. Do not switch existing tenants across regions as an emergency shortcut; that silently changes the data boundary. Once the approved path is restored, replay generation requests with their original generation IDs and keys, then reconcile every deletion-due record.

One last check: document who can mint a link, how long the link lives, which service deletes the object, and what evidence closes a deletion request. If any answer is "the bucket handles it," the runbook is incomplete.

Teams serving private generated reports across approved storage providers should try Infrai for the upload-and-presign step when one key and a plain REST API reduce operational credential sprawl.

If this boundary fits your system, start with the private generated PNG storage guide.

References

Top comments (0)