DEV Community

Implement Direct-to-Storage Browser Uploads for Web Apps - Node.js Explained

Short answer: implement direct-to-storage browser uploads with a short-lived, single-object authorization, then verify the stored object before marking the media receipt complete.

For a media web app that receives large receipt files, the simplest reliable design is a short-lived upload authorization from the backend, followed by a browser upload directly to object storage.

The backend should record an immutable receipt before it grants that authorization: tenant, object key, expected size, content type, checksum policy, and an expiration time. The browser transfers bytes; the application remains the authority for what those bytes mean. That separation matters more than the storage brand.

A receipt processor may accept a 2 GB scan today and need to answer an auditor's question about it months later. Sending that file through the application server adds a throughput bottleneck and makes retries harder to reason about. Direct upload removes the large body from the application path, but it does not remove the need for idempotency, authorization, reconciliation, or an audit trail.

How should web apps implement direct-to-storage browser uploads?

There are three deliberately boring steps.

  1. The browser asks the application for an upload session.
  2. The application validates the authenticated user and creates a unique object key, then returns a narrowly scoped signed upload request.
  3. The browser uploads the file and calls the application again with the session identifier.

A worker or storage event can verify completion, but the application must not treat a client-side โ€œsuccessโ€ message as proof that durable bytes exist. That is the whole data-plane decision.

The session is the boundary between intent and evidence. I use a state transition such as created -> authorized -> observed -> verified, with terminal rejected and expired states. A repeated completion request must return the existing result for the same session rather than create a second receipt. That is an exactly-once mindset applied to business state, because the network itself will deliver neither exactly once nor in a useful order.

The object key should be opaque and generated by the server. It should not contain an invoice number supplied by the browser, and it should not be reused after a failed attempt. Store the original filename as metadata in the receipt record, where it can be escaped and displayed safely; keep it out of authorization decisions and storage paths.

Why is large-file throughput a storage decision, not an upload trick?

The constraint is the path of the bytes. With a proxy upload, the browser sends the file to the application, the application receives it, and the application sends it onward. Even with streaming, the service pays in connection occupancy, bandwidth, backpressure, and failure coordination. Direct upload leaves the application handling small control-plane requests while the storage service handles the data plane.

Large objects still need a transfer policy. A single request is easy to implement but gives a poor recovery point when a connection fails near the end. Multipart or resumable protocols improve retry granularity, at the cost of tracking parts, completion ordering, abandoned uploads, and a finalization call. The right comparison is not โ€œwhich API has the nicest exampleโ€; it is โ€œhow much state can the team operate correctly when a 1.8 GB upload is interrupted after 1.7 GB?โ€

Consider the receipt that reaches 1.7 GB and then loses its connection. A proxy service can retry from its own stream only if it has retained enough state, while a direct upload can retry the affected part if the protocol supports it. That sounds like a throughput win until the completion record is considered: an orphaned multipart upload may consume storage, a late completion may race with an expiry job, and a browser retry may use a different session unless the client preserves the original identifier.

I would therefore make the first implementation single-request for files below the known operational limit, with a documented rejection above it, and introduce resumable transfer only after measuring the failure rate and the reconciliation workload. That is a less impressive demo, but it produces a smaller state machine and a clearer audit explanation while the media workflow is still changing.

Keep it explicit. The storage interface is broadly similar across common choices, but the boundaries differ. Amazon S3 uses presigned URLs for time-limited requests. Google Cloud Storage provides signed URLs, and Azure Blob Storage uses shared access signatures. Cloudflare R2 documents an S3-compatible API and presigned URLs. These mechanisms are useful evidence of a common pattern, not interchangeable promises: signing syntax, multipart behavior, checksum support, lifecycle controls, and event delivery must be checked against the selected service's current documentation.

Option Access mechanism Useful boundary
S3-compatible storage Presigned request Check multipart and checksum semantics separately
Google Cloud Storage Signed URL Confirm the signing and regional policy fit
Azure Blob Storage Shared access signature Scope permissions and expiry precisely

The table is a comparison of control surfaces, not a ranking. A team already operating one provider may rationally prefer its operational tooling even when another API looks shorter in a tutorial.

A minimal authorization endpoint in Go

The important part of this example is the contract, not a vendor SDK. The signer is an injected interface, so the policy can be tested without uploading bytes.

package upload
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"time"
)
type Signer interface {
SignPut ( key , contentType string , expires time . Duration ) ( string , error )
}
type SessionStore interface {
Create ( userID , key , contentType string , size int64 , expiresAt time . Time ) error
}
type AuthorizeHandler struct {
Signer Signer
Store SessionStore
}
type authorizeRequest struct {
ContentType string `json:"content_type"`
Size int64 `json:"size"`
}
type authorizeResponse struct {
SessionID string `json:"session_id"`
ObjectKey string `json:"object_key"`
UploadURL string `json:"upload_url"`
ExpiresAt time . Time `json:"expires_at"`
}
func ( h AuthorizeHandler ) ServeHTTP ( w http . ResponseWriter , r * http . Request ) {
var in authorizeRequest
if json . NewDecoder ( r . Body ) . Decode ( & in ) != nil || in . Size <= 0 || in . Size > 2 << 30 {
http . Error ( w , "invalid upload" , http . StatusBadRequest )
return
}
var idBytes [ 16 ] byte
if _ , err := rand . Read ( idBytes [ : ] ) ; err != nil {
http . Error ( w , "unable to create session" , http . StatusInternalServerError )
return
}
sessionID := hex . EncodeToString ( idBytes [ : ] )
key := "receipts/" + sessionID
expiresAt := time . Now ( ) . Add ( 10 * time . Minute )
if err := h . Store . Create ( r . Context ( ) . Value ( "user_id" ) . ( string ) , key , in . ContentType , in . Size , expiresAt ) ; err != nil {
http . Error ( w , "unable to create session" , http . StatusInternalServerError )
return
}
url , err := h . Signer . SignPut ( key , in . ContentType , 10 * time . Minute )
if err != nil {
http . Error ( w , "unable to authorize upload" , http . StatusInternalServerError )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( authorizeResponse { sessionID , key , url , expiresAt } )
}

In production I would make the authenticated identity an explicit handler dependency rather than retrieve it with a type assertion, and I would persist the session before returning the URL. The example keeps the two points visible: the client cannot choose the key, and the authorization expires independently of the browser tab.

The completion endpoint should perform a conditional state transition. It can ask storage for object metadata, compare size and content type with the session, and record the provider's version or generation identifier when available. A checksum is stronger evidence than a browser-reported byte count. If the storage system supports a server-side checksum or immutable version identifier, preserve it in the receipt record. Do not let a second completion request overwrite a verified record.

What fails in real deployments?

The first failure is authorization scope. A URL that permits an arbitrary key, content type, or long lifetime has turned a small upload feature into an unbounded write capability. Bind the request to one server-generated key, enforce size and type at the storage boundary where possible, and keep the lifetime short enough that leaked credentials have a limited window. The limitation is deliberate: direct upload is a poor fit when every byte must be transformed or inspected before storage. In that case, a controlled ingestion service or streaming scanner belongs in the path, even though it costs throughput and operational complexity.

The second is treating object existence as business completion. A file can exist without a valid receipt row, or a receipt row can exist after a client abandoned its upload. Reconciliation closes that gap: periodically find sessions stuck in authorized, compare them with storage metadata, and move them to expired, verified, or needs_review according to explicit rules. Keep the reconciliation result in the audit trail; an auditor needs to see the correction, not only the final state.

The third is retry ambiguity. Browser retries, worker retries, webhook retries, and operator replays are normal. Give every session and completion request an idempotency key, use a unique database constraint, and make state transitions conditional on the current state. โ€œExactly onceโ€ is a business invariant you implement with durable records and constraints, not a transport property you assume.

Compliance limits belong in the design review. A signed URL is a bearer capability, not proof of the end user's identity. Access logs, retention rules, deletion holds, encryption configuration, regional processing requirements, and audit-log access are separate controls. Object storage can preserve the original file, but it cannot decide whether a receipt should be retained for seven years or deleted under a valid request.

A restrained rollout plan

Start with one receipt type and a hard maximum size. Measure upload duration, authorization failures, abandoned sessions, verification lag, and reconciliation volume; throughput alone will hide the cases that matter to an audit. Test expired URLs, duplicate completion calls, truncated bodies, mismatched metadata, and a storage outage between upload and verification. Use fake signers in unit tests and a disposable bucket in integration tests, then run a small production cohort with a manual reconciliation report.

After the state machine is boring, add multipart or resumable transfer for files that justify its operational cost. Add lifecycle cleanup for incomplete parts and expired sessions. Keep the public API stable while the data plane evolves. That is the useful meaning of โ€œsimpleโ€ here: a browser uploads directly, while the backend retains enough durable evidence to explain every accepted file.

Sources

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.