Implement Direct-to-Storage Browser Uploads for Web Apps — 4 Tenant Rules Explained
Short answer: issue a short-lived, single-object upload capability only after the application has authenticated the user and resolved the tenant. Let the browser send bytes to object storage, then make the application ve
Short answer: issue a short-lived, single-object upload capability only after the application has authenticated the user and resolved the tenant. Let the browser send bytes to object storage, then make the application verify the resulting object before it becomes part of the product. The simplest design is therefore a small authorization endpoint plus one browser upload, not a file relay hidden behind the web server.
For a B2B SaaS product handling large recordings, this decision keeps media bytes away from the application path while making tenant isolation the first-class rule. A signed URL, SAS token, or equivalent is a temporary capability. It is not a substitute for authorization. The server still decides who may upload, where the object may land, how large it may be, and what happens after completion.
How should web apps implement direct-to-storage browser uploads?
The flow has four steps. The browser asks the application for an upload grant. The application authenticates the session, selects a tenant-owned object key, and asks a storage adapter for a time-limited write capability. The browser uploads directly to storage with that capability. Finally, the application records or validates the object after the storage service reports completion.
That ordering matters. A client-supplied tenantId is input, not authority. The object key should be derived from the authenticated tenant and a server-generated upload identifier. A useful key might look like tenant_42/uploads/01J.../session-recording.mp4; the exact naming convention is less important than making cross-tenant placement difficult to do accidentally.
Keep it boring.
Here is the narrow application boundary I would start with. The storage-specific signing code stays behind signUpload, so changing providers does not spread through the browser client or the authorization rules.
type UploadRequest = {
fileName: string;
contentType: string;
sizeBytes: number;
};
type UploadGrant = {
uploadId: string;
objectKey: string;
uploadUrl: string;
expiresAt: string;
};
async function createUploadGrant(
user: { id: string; tenantId: string },
input: UploadRequest,
): Promise<UploadGrant> {
if (!/^video\/(mp4|webm)$/.test(input.contentType)) {
throw new Error("unsupported media type");
}
if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes <= 0) {
throw new Error("invalid size");
}
const uploadId = crypto.randomUUID();
const safeName = input.fileName.replace(/[^a-zA-Z0-9._-]/g, "_");
const objectKey = `tenants/${user.tenantId}/uploads/${uploadId}/${safeName}`;
const uploadUrl = await signUpload({
objectKey,
contentType: input.contentType,
contentLength: input.sizeBytes,
expiresInSeconds: 300,
});
await savePendingUpload({
uploadId,
tenantId: user.tenantId,
requestedBy: user.id,
objectKey,
sizeBytes: input.sizeBytes,
contentType: input.contentType,
});
return {
uploadId,
objectKey,
uploadUrl,
expiresAt: new Date(Date.now() + 300_000).toISOString(),
};
}
async function putFromBrowser(file: File, grant: UploadGrant): Promise<void> {
const response = await fetch(grant.uploadUrl, {
method: "PUT",
headers: { "Content-Type": file.type },
body: file,
});
if (!response.ok) {
throw new Error(`upload failed: ${response.status}`);
}
await fetch(`/uploads/${grant.uploadId}/complete`, { method: "POST" });
}
signUpload and savePendingUpload are deliberately generic interfaces, rather than a product setup recipe. A real adapter must bind the signed request to the intended object key and content type, and the completion endpoint must authenticate the same user before changing the pending record. The browser can display progress and retry an expired grant; it should never be trusted to report a different tenant, object key, or final size.
Which boundary stops the expensive mistakes?
Tenant isolation is a chain, not a prefix pasted onto a path. Check the tenant at grant creation, store the tenant beside the pending upload, and check it again when a completion event or client callback arrives. A database uniqueness rule on uploadId and tenant can make accidental reuse visible. Object storage policy can provide another boundary, but policy should reinforce the application decision rather than carry all of it.
The common failure is granting a broad capability because it is easier to implement. A bucket-wide write token, a reusable URL, or a key assembled from a browser-supplied account name turns a small upload feature into an authorization problem with a large blast radius. Keep the capability narrow: one object, one method, one expected content type, and a short expiry.
The second failure is treating a successful HTTP upload as proof that the product can safely use the file. Record an upload as pending before the transfer. On completion, verify that the object belongs to the pending record and that its observed metadata meets the policy. If media processing is asynchronous, enqueue it only after that check. Deleting abandoned pending objects is an operational policy, not a reason to accept arbitrary callbacks. The trade-off is deliberate: more state in exchange for a smaller tenant-level failure.
There is a trade-off here. Requiring a completion step adds state and one more request, but it gives the product an explicit place to reject stale, duplicated, or cross-tenant notifications. For a multi-tenant media workflow, that state is cheaper than debugging an orphaned object that was attached to the wrong customer.
How do the storage options differ without changing the design?
The architecture survives provider changes because the capability has a common meaning even when the wire details differ. Amazon S3 documents presigned URLs for uploading an object without giving the browser storage credentials. Google Cloud Storage documents signed URLs for time-limited access to a specific resource and operation. Azure Blob Storage uses shared access signatures, which can scope permissions and duration. Cloudflare R2 documents S3-compatible presigned URLs for browser uploads. These are related mechanisms, not interchangeable configuration files.
The practical differences belong in the adapter and test suite. S3-style signing commonly makes the HTTP method, object key, headers, and expiry part of the signature. A GCS signed URL has its own signing and canonical-request rules. An Azure SAS expresses permissions through its token format and supports blob-oriented resource scopes. An R2 S3-compatible endpoint still needs its endpoint, region behavior, CORS policy, and signing inputs configured for that service.
| Option | Browser access pattern | Good fit | Boundary to test |
|---|---|---|---|
| Amazon S3 | Presigned REST request | S3-compatible object workflows | Signed method, key, and headers |
| Google Cloud Storage | Signed URL request | Resource-scoped time-limited access | Canonical request and expiry |
| Azure Blob Storage | SAS-authorized blob request | Blob-specific permissions | Token permissions and resource scope |
| Cloudflare R2 | S3-compatible presigned request | S3-shaped client adapters | Endpoint, CORS, and signing inputs |
The table is a map for adapter tests, not a ranking. The application-level tenant rule stays the same.
Do not make the browser know these distinctions. Expose one internal result such as UploadGrant, and test the adapter against the provider's documented request shape. Portability is not pretending every storage service has identical semantics; it is keeping provider assumptions in one place where they can be reviewed.
CORS is another boundary people discover late. The browser must be allowed to send the intended method and headers to the storage origin, and the application origin must be allowed to call the grant and completion endpoints. A CORS rule that is too broad can expose a capability to more web origins than intended; one that is too narrow looks like an upload authorization failure in the browser. Treat it as a deployment setting with an automated smoke test, not as a frontend detail.
What should fail in tests before production?
Test the decision, not just the happy-path PUT. A user from tenant A must not receive a grant for tenant B even when the request body names tenant B. A grant must reject an altered object key, method, or signed content type. An expired grant must fail. A completion request from a different authenticated tenant must leave the pending record unchanged. Two completions for the same upload should be idempotent or produce a clearly handled conflict.
Use a small matrix of files: the maximum accepted size, one byte over it, an allowed media type, a disallowed type, a filename with path separators, and a file that uploads successfully but fails later media validation. Add a browser-level test for CORS and a storage-adapter test for each supported provider. The point is not to emulate every storage implementation in one mock. The point is to catch when a provider-specific assumption leaks into tenant authorization.
Observability should attach tenantId and uploadId to application logs, while avoiding raw signed URLs because those URLs are bearer capabilities. Record grant creation, upload completion, validation result, bytes expected, and bytes observed. Keep object keys and identifiers searchable, but do not log the capability itself. Alerts are more useful when they distinguish expired grants, rejected policy, storage errors, and completion mismatches instead of counting all failed uploads together.
Cost belongs in the same review, although it should not drive the security boundary. Direct upload removes application egress and request-body handling from the hot path, but it still creates storage operations, retained objects, retries, and downstream processing. A client retry after an ambiguous network result can create a new object or repeat a write depending on the protocol and key strategy. An upload identifier and explicit lifecycle cleanup make those cases visible.
The state machine is where the implementation earns its keep. Start with pending, because a grant means that an upload was authorized, not that bytes arrived. Move to received only after the storage response or an equivalent provider event can be tied to the exact object key recorded for that tenant. Move to accepted only after metadata and media validation pass. A rejected object should be inaccessible to normal product reads and eligible for cleanup. This distinction handles several awkward cases without pretending the network is perfectly reliable: the browser may lose its connection after storage has accepted the request; a completion request may be retried by the client; a worker may process the same event twice; or a user may close the tab after receiving a grant and never upload anything. Each case has a different next action, but all of them can be represented by the same upload identifier and an explicit transition rule. The database record is not a copy of object storage; it is the application’s claim about what the object is allowed to become. Keeping that claim tenant-scoped makes later authorization checks straightforward, while keeping the raw capability out of logs limits the damage if operational data is exposed. This is a little more ceremony than setting a URL in a form, but it is also the part that lets support staff answer which customer owns an object without inspecting arbitrary bucket paths.
The operational checklist is short enough to keep beside the implementation: authenticate before signing; derive the key from server-owned tenant data; bind the capability to one object and expected metadata; keep expiry short; configure exact CORS origins; persist a pending record; validate before publishing; make completion idempotent; expire abandoned uploads; and never log the signed capability. That is the smallest design I would trust for large media in a multi-tenant SaaS application.
The conclusion is a decision rule. Use direct-to-storage uploads when the browser can reach the storage origin and the application can enforce a per-object capability. Keep the application in charge of identity, tenant ownership, validation, and lifecycle. Keep storage in charge of receiving bytes. The simplicity comes from separating those jobs, not from removing the checks.
References
- Amazon S3 presigned upload URLs: https://docs.aws.amazon.com/AmazonS3/latest/userguide/PresignedUrlUploadObject.html
- Google Cloud Storage signed URLs: https://cloud.google.com/storage/docs/access-control/signed-urls
- Azure Blob Storage shared access signatures: https://learn.microsoft.com/en-us/azure/storage/blobs/sas-service-create-javascript
- Cloudflare R2 presigned URLs: https://developers.cloudflare.com/r2/api/s3/presigned-urls/
- MDN Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.