Presigned URLs for Browser Uploads: Explained Through Object Storage Retention
Choose signed upload tokens when the browser should send bytes directly to object storage, but keep authorization, retention, and deletion in your application. The token is a short-lived capability. It is not your tenant
Choose signed upload tokens when the browser should send bytes directly to object storage, but keep authorization, retention, and deletion in your application. The token is a short-lived capability. It is not your tenant boundary.
TL;DR: create an upload intent on the server, bind it to one tenant and one object key, sign a narrowly scoped request, verify the completed object, and make deletion a first-class workflow. For a one-person SaaS, this keeps the hot path small while leaving the expensive, undifferentiated byte transfer to storage infrastructure.
| Decision | Default choice | Reason |
|---|---|---|
| Who chooses the object key? | Server | Prevents tenant-controlled paths and accidental overwrites |
| How long is the browser grant valid? | Minutes, not hours | Limits the damage of a leaked URL |
| Where is ownership recorded? | Application database | Storage metadata alone is not a tenant policy |
| How is completion accepted? | Server-side verification | A request being sent does not prove a usable image exists |
| How is removal handled? | Database state plus object deletion | Retention must cover both records and bytes |
The recommendation is deliberately boring: treat an upload as a state transition, not as a URL-generation endpoint. That decision matters more than the storage brand.
How should I implement presigned URLs for browser uploads?
A useful grant answers five questions before it reaches the browser: which tenant, which object, which HTTP method, which content constraints, and which expiration. The server should generate an opaque object key such as tenants/t_482/assets/01J.../original.webp; it should never accept a raw path supplied by the browser and quietly append it to a tenant prefix.
The database row can start in created, move to uploaded after verification, and end in deleted or expired. The signed URL is only the temporary permission for the created state. It should not be the source of truth for ownership.
A short expiry does not solve every problem. A hostile page can use a valid URL before it expires, and a client can retry after a network timeout. Bind the request to the intended method and, where the signing protocol supports it, the expected content type and length. Enforce the same limits again when the server inspects the completed object. Defense in depth is useful here because the browser is an untrusted caller.
Why is retention harder than the upload?
Uploading one image is an event. Retention is a policy.
Keep it boring.
For a product catalog, I would model the image record with tenant_id, object_key, media_state, created_at, deleted_at, and an optional expires_at. A tenant-scoped export should select records by tenant_id in the application query, then read only the exact keys returned by that query. A storage prefix is helpful organization; it is not an authorization check.
Deletion needs a retryable job. Mark the database record as pending deletion, remove the object, then record the result. If the object is already gone, treat that as an idempotent success. If the storage call fails, keep the record visible to the job queue and alert on age, rather than declaring the tenant's data gone because one request returned. The business promise is deletion, not an optimistic button click.
This is also where legal and product requirements meet. GDPR Article 17 describes a right to erasure, subject to its stated conditions and exceptions. It does not prescribe your object key layout. Your system still needs a discoverable mapping from tenant records to bytes, including derivatives and export artifacts.
A small implementation boundary that survives retries
The following TypeScript-style boundary shows the important shape. The signer is an interface, so the rest of the application does not depend on a particular storage provider. The example intentionally returns an upload intent rather than exposing a general-purpose signing function.
type UploadIntent = {
id: string;
tenantId: string;
objectKey: string;
contentType: string;
maxBytes: number;
expiresAt: Date;
};
interface ObjectSigner {
signPut(input: {
key: string;
contentType: string;
maxBytes: number;
expiresAt: Date;
}): Promise<string>;
}
async function createUploadIntent(
tenantId: string,
input: { filename: string; contentType: string; size: number },
signer: ObjectSigner,
db: { insert: (row: UploadIntent) => Promise<UploadIntent> }
): Promise<{ intentId: string; uploadUrl: string }> {
const maxBytes = 10 * 1024 * 1024;
if (input.size > maxBytes || !input.contentType.startsWith("image/")) {
throw new Error("unsupported upload");
}
const intent: UploadIntent = {
id: crypto.randomUUID(),
tenantId,
objectKey: `tenants/${tenantId}/assets/${crypto.randomUUID()}`,
contentType: input.contentType,
maxBytes,
expiresAt: new Date(Date.now() + 5 * 60 * 1000)
};
const saved = await db.insert(intent);
const uploadUrl = await signer.signPut(intent);
return { intentId: saved.id, uploadUrl };
}
The number 5 * 60 * 1000 is a policy example, not a universal setting. Pick it from the time a real user needs to select and upload a file, then add a margin for slow networks. Keep the maximum size aligned with the server's post-upload checks. If these values drift, the browser receives confusing failures and the operator gets an avoidable support ticket.
The completion endpoint should authenticate the user again, load the intent by ID, confirm the tenant matches, inspect object metadata, and transition the row once. A repeated completion request should return the existing result. That is the retry behavior users expect after a lost response.
What belongs in the test and operations loop?
Test the boundaries, not only the happy upload. Try a URL with an expired timestamp, a different object key, an unexpected content type, an oversized object, a completion request from another tenant, and two completion requests arriving together. Add a property test for key generation if your path rules are complex. Small tests here protect the data model more effectively than a large browser-only test.
For operations, measure intent age, completion rate, rejected object count, pending-deletion age, and export failures by tenant. Do not log signed URLs. They are bearer capabilities, and logs tend to outlive the URL's advertised lifetime. Log the intent ID and a hashed or internal reference to the object instead.
The cost decision is mostly about engineering time. Direct upload avoids making the application server a byte proxy, but it creates a little state machinery: intent records, verification, cleanup, and metrics. I accept that machinery because it is reusable across avatars, catalog images, and tenant exports. The boundary pays rent every week.
When is a different upload design better?
A browser-to-application upload can be the better choice when files are tiny, content inspection must happen before storage, or the application already needs to transform every byte synchronously. A multipart upload is better for large files or unreliable networks, where resumable parts justify more orchestration. A managed media pipeline can be reasonable when image transformations and scanning are the product requirement, and operating those workers would distract from revenue-producing work.
The decision rule stays the same: choose the smallest path that makes tenant ownership, retention, and deletion observable. Signed URLs are a transport mechanism. The durable product behavior lives in the intent record and its state transitions.
The limitation is operational complexity. This design is a poor fit if the team cannot maintain cleanup jobs, object inspection, and tenant-aware audit records. In that case, routing bytes through an existing application workflow may be the more defensible trade-off, even though it consumes application capacity. The right choice is the one whose failure modes the team can observe and repair.
References
- https://gdpr-info.eu/art-17-gdpr/
- https://www.rfc-editor.org/rfc/rfc9110
- https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL_static
- https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html Deletion needs a retryable job. Mark the database record as pending deletion, remove the object, then record the result. If the object is already gone, treat that as an idempotent success. If the storage call fails, keep the record visible to the job queue and alert on age, rather than declaring the tenant's data gone because one request returned. The business promise is deletion, not an optimistic button click.
There is a practical sequence behind that rule. First, the user action records an intent to remove the database row and its object key. Next, a worker claims the job with a lease so two workers do not perform the same expensive work at once. It asks storage to remove the exact key, records an idempotent success when the key is already absent, and leaves a retry count when the provider returns a transient error. A later audit can then answer a narrow question: which tenant-owned bytes still have a live record, and which records are waiting for repair? That question is more valuable than a dashboard showing only total delete requests.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes â full credit and traffic to the original publisher.