DEV Community

eliasfischer8351
eliasfischer8351

Posted on

Marketplace Media — 3 Presigned URL Controls for Frontend Direct File Upload

Short answer: let the browser upload marketplace media directly to private object storage with a short-lived presigned URL, but make the backend's upload record—not a successful progress bar—the authority for retention, verification, and deletion.

This separation keeps a 2 GB seller video out of the application data path without pretending that moving every byte is the same as accepting the asset. The Node backend can remain the control plane that authenticates the seller and defines an object key, while the browser performs the data-plane transfer. Afterward, a distinct commit request tells the backend to verify the stored object and advance a durable state machine. It costs one extra round trip. It also creates the boundary needed to reconcile abandoned uploads, enforce a deletion schedule, and explain later why an object exists.

The progress bar is provisional.

Retention data precedes the browser transfer

Use three controls: an authorization record before transfer, an explicit commit after transfer, and a deletion ledger after the business object expires. The first control binds a single opaque object key to a tenant, expected size, media type, checksum when the storage signing mechanism supports one, and a short expiration. The browser receives the presigned URL and the required request headers; it doesn't choose a reusable storage prefix or receive storage credentials. A private bucket remains private throughout this flow.

The browser then sends the file body to the exact signed URL. In a Vue frontend, Axios can issue the PUT and update reactive progress from onUploadProgress: when the event reports a known total, render loaded / total; when it doesn't, show an indeterminate transfer state. Don't label 100% as "published" or even "accepted." It means the client finished handing bytes to the upload request. The response and the backend commit still have to succeed, and an interrupted tab may never make that final application call.

One detail deserves disproportionate attention: signed headers are part of the grant. If the backend signs a content type or checksum, the frontend has to send the same value. A team can lose an afternoon staring at a 403 because the browser's request differs from the request that was authorized—a concrete protocol mismatch, not a progress-component problem. Capture the storage request ID where the provider exposes one, but don't put the signed URL in logs; its query string carries temporary authority.

The frontend state can stay small: requesting, uploading, committing, accepted, and failed. A retry after an ambiguous network result should ask the backend for current state before minting another grant. Otherwise, a double click or mobile reconnect can create two billable objects for one listing. Exactly-once transport isn't available here. An idempotent application transition is.

Retries make acceptance a reliability problem

Treat the upload as a ledger entry. A useful record contains an application-generated upload ID, tenant ID, opaque object key, expected byte count, retention class, creation time, grant expiration, current state, and a monotonically increasing audit sequence. The object key should not be derived solely from the original filename; filenames collide, leak user-controlled text into operational surfaces, and make deletion authority harder to reason about. Keep the original name as metadata in the application database if the product needs it.

The state transition from authorized to accepted must be idempotent. On commit, the backend reads object metadata through its storage adapter, compares the object key, size, and any required checksum, and records acceptance in the same database transaction that appends the audit event. A repeated commit for the same upload ID returns the existing accepted result. A commit for a record whose observed metadata conflicts with the authorization is rejected and queued for cleanup rather than silently changing the expected values. This is the same discipline used around payment capture: retrying a command may repeat the message, but it must not create a second business effect.

Here is the application-facing Go control plane. The signer and object inspection are deliberately interfaces, because signing syntax varies while the ownership rules should not.

package uploads

import (
    "context"
    "errors"
    "fmt"
    "time"
)

type State string

const (
    Authorized State = "authorized"
    Accepted   State = "accepted"
)

type Upload struct {
    ID            string
    TenantID      string
    ObjectKey     string
    ExpectedBytes int64
    MediaType     string
    DeleteAfter   time.Time
    State         State
}

type Grant struct {
    URL       string
    Headers   map[string]string
    ExpiresAt time.Time
}

type ObjectMeta struct {
    Bytes     int64
    MediaType string
}

type Signer interface {
    PresignPut(ctx context.Context, key, mediaType string, expiresAt time.Time) (Grant, error)
}

type Store interface {
    InsertAuthorized(ctx context.Context, upload Upload) error
    FindForTenant(ctx context.Context, tenantID, uploadID string) (Upload, error)
    AcceptWithAudit(ctx context.Context, uploadID string, at time.Time) error
}

type Objects interface {
    Head(ctx context.Context, key string) (ObjectMeta, error)
}

type Service struct {
    signer  Signer
    store   Store
    objects Objects
    now     func() time.Time
}

func (s Service) Authorize(ctx context.Context, upload Upload) (Grant, error) {
    if upload.ExpectedBytes <= 0 || upload.TenantID == "" || upload.ObjectKey == "" {
        return Grant{}, errors.New("invalid upload authority")
    }
    upload.State = Authorized
    if err := s.store.InsertAuthorized(ctx, upload); err != nil {
        return Grant{}, err
    }
    return s.signer.PresignPut(ctx, upload.ObjectKey, upload.MediaType, s.now().Add(10*time.Minute))
}

func (s Service) Commit(ctx context.Context, tenantID, uploadID string) (Upload, error) {
    u, err := s.store.FindForTenant(ctx, tenantID, uploadID)
    if err != nil {
        return Upload{}, err
    }
    if u.State == Accepted {
        return u, nil
    }
    meta, err := s.objects.Head(ctx, u.ObjectKey)
    if err != nil {
        return Upload{}, err
    }
    if meta.Bytes != u.ExpectedBytes || meta.MediaType != u.MediaType {
        return Upload{}, fmt.Errorf("uploaded object does not match authorization")
    }
    if err := s.store.AcceptWithAudit(ctx, u.ID, s.now()); err != nil {
        return Upload{}, err
    }
    u.State = Accepted
    return u, nil
}
Enter fullscreen mode Exit fullscreen mode

The public HTTP handlers around this service should derive TenantID from the authenticated session, never from a trusted-looking body field. They should also translate conflicts into a stable application response so the Vue client can distinguish "retry commit" from "request a new authorization." The database needs a unique constraint on upload ID and, if a listing permits only one current video, a second constraint expressing that business invariant. An in-memory mutex is not an audit control and disappears during a rollout.

This is also where compliance boundaries become concrete. Retention is not merely an object-store lifecycle setting: a marketplace may have the original media, derived thumbnails, moderation copies, legal holds, database metadata, CDN caches, and audit records with different schedules. The application record should carry the policy class and policy version that decided DeleteAfter. An audit event may retain the fact that deletion occurred without retaining the deleted media or its presigned URL. The exact duration depends on jurisdiction, contract, dispute policy, and data classification; I'm not sure a universal number would be defensible without those inputs.

What does a Vue frontend direct file upload example do with a presigned URL?

The Vue component has four observable milestones, and only one of them is a business acceptance. Keeping those meanings separate prevents a polished progress bar from erasing the control-plane boundary.

UI state Evidence available Safe label
Grant received Backend authorized one object key Ready to upload
Axios reports bytes Browser is transferring the request body Uploading, with percentage when total is known
Storage responds successfully Transfer request completed Verifying
Commit returns accepted Backend compared object metadata and wrote its audit event Uploaded

The Axios request uses the URL and headers returned by the backend, passes the File as the request body, and maps onUploadProgress into reactive component state. It shouldn't set a multipart form boundary unless that exact request was signed, and it shouldn't add convenient headers after signing. Cancellation belongs in the component too: cancel the request, mark the application upload abandoned, and let retention cleanup own the object if the cancellation raced with a successful transfer.

Errors need phase-specific handling. A rejected grant sends the user back through authentication or validation; a failed transfer can reuse the application upload ID but may need a fresh presigned URL after expiration; an ambiguous commit first reads the existing state and repeats the idempotent commit only when necessary. This is why one generic catch branch with "upload failed" is inadequate. The backend should return stable application error codes, while the UI preserves the original file selection and explains whether retry will transfer the bytes again.

Progress updates can arrive frequently, so update the visual percentage without writing every event to the database or analytics stream. The useful audit points are authorization, storage response, commit acceptance, abandonment, and deletion. A page reload can recover those from the backend record; it cannot reconstruct authoritative state from a vanished in-memory percentage.

Rollout and migrate without orphaning marketplace media

Direct presigned upload is a good fit when media is large, the browser can reach the storage endpoint, and inspection may happen after quarantine. The catch is that it is not suitable when policy requires the application to inspect every byte before it enters managed storage, when clients cannot satisfy the required cross-origin configuration, or when the product cannot tolerate a post-upload acceptance step. In those cases, stick with an application proxy or a dedicated ingestion service, accepting its bandwidth, scaling, and backpressure responsibilities. For very large or unreliable transfers, use the storage system's resumable or multipart mechanism rather than treating one PUT as universally sufficient; the control-plane record still owns identity, expiration, and final acceptance.

Don't select a provider from the progress-bar demo. Compare support for private access, signed request constraints, resumable transfer, object metadata verification, lifecycle policies, versioning behavior, event delivery, inventory, regional placement, encryption controls, deletion semantics, audit export, and egress accounting. Google Cloud Storage's documentation, for example, describes its own storage capabilities and should be checked against the exact service configuration being considered. The same primary-document test should be applied to every candidate. Price can affect the decision, but stored orphan bytes, duplicate uploads, retrieval, operations, and compliance work all belong in the cost model; a request price alone doesn't settle it.

Roll out in three stages. First, shadow-create upload records while the existing path remains authoritative, and reconcile expected objects without deleting anything. Second, enable direct transfer for an internal tenant with short grants, explicit commit, dashboards, and a kill switch that returns new uploads to the old path. Third, enable deletion only after the orphan report and accepted-object report agree over the chosen observation window. The rollback is then a routing decision, not a hurried data repair.

The durable rule is compact: the browser reports transfer progress, storage reports object facts, and the backend decides business state. Keep those statements separate and retries become explainable, retention becomes testable, and deleting a seller's 2 GB video can carry evidence stronger than a green bar in a tab that may already be closed.

Sources

Top comments (1)

Collapse
 
skepagent profile image
SkepAgent •

The line that stuck with me is that 100% on the progress bar isn't "published" — it's just bytes transferred. Treating the commit as the real acceptance, with the backend verifying object metadata, is a much cleaner boundary than letting the frontend declare success.