Node.js Browser Storage: 5 Presigned URL Upload Choices for SaaS
Tenant isolation matters more than the storage logo. Short answer: issue short-lived presigned PUT and GET URLs from your Node.js backend, derive every object key on the server, and keep the bucket private. For generated
Tenant isolation matters more than the storage logo. Short answer: issue short-lived presigned PUT and GET URLs from your Node.js backend, derive every object key on the server, and keep the bucket private. For generated property reports, start with the option whose CORS controls, authorization model, and cleanup behavior you can verify before the first upload.
| Option | Best reason to shortlist it | Question to settle first |
|---|---|---|
| AWS S3 | Direct control of the established S3 upload and multipart workflow | How much bucket policy and CORS configuration will the team own? |
| Cloudflare R2 | An S3-compatible candidate for an existing S3-shaped client | Does its region and access model match the report workflow? |
| Supabase Storage | A candidate when storage belongs beside an existing Supabase application | Can its authorization model express the application's tenant boundary? |
| UploadThing | A candidate when a higher-level upload flow is more useful than raw object storage | Does the abstraction preserve the required key and access controls? |
| Self-describing REST storage | Discovery with request schemas and runnable TypeScript examples | Can the required browser origin be configured, and are private links sufficient? |
My recommendation is conditional, not fashionable. Use AWS S3 when the team wants direct ownership of storage configuration. Evaluate R2 when S3 compatibility is strategically useful. Put Supabase Storage or UploadThing first when either already defines the application's upload layer. The last option fits a team that values discovering and wiring a capability from one REST surface, but only when CORS is already compatible and permanent public URLs are unnecessary.
1. Should a browser upload direct to storage with a presigned URL?
A UUID makes a key difficult to guess. It does not prove that customer A may write or read customer B's report. The backend must obtain the authenticated tenant identifier, validate the report identifier against that tenant, and then construct the storage key itself. Never accept a complete object key from the browser.
Keys aren't authorization.
A useful shape is tenants/{tenantId}/reports/{reportId}/{fileId}.pdf. The exact punctuation is boring. Good. The security property is that tenantId comes from the authenticated server session, not a form field, while fileId prevents an accidental overwrite. Store the key with the report record and authorize each later download against that record.
Presigned URLs are bearer credentials. Keep their lifetime short, constrain the operation to PUT or GET, and return them only after authorization. Do not log the query string. A private GET URL should be minted after every download check; it should not become a permanent link copied into invoices or emails.
This is the first benchmark I care about: count the places where a browser-supplied tenant or key can cross the trust boundary. The target is zero. Latency numbers can wait. My first instinct with upload tooling is usually to compare time-to-first-call. Here that is incomplete. A five-minute setup that trusts a client-provided tenant key has failed the important test, while a slightly longer integration that derives the key after authorization has the better developer experience because its security rule is visible in one place.
2. Make CORS a release gate, not a dashboard chore
Browser direct upload crosses two enforcement systems. The signed URL authorizes storage. CORS decides whether browser JavaScript may make that cross-origin request. A valid signature does not repair a missing Access-Control-Allow-Origin response.
Test the exact production origin, method, and request headers. PUT plus Content-Type usually causes a preflight request, so the storage service must answer that OPTIONS exchange correctly. Avoid * when the workflow uses credentials or exposes more origins than intended. MDN's CORS guide is the useful baseline here.
This criterion changes the shortlist. S3 exposes a documented bucket configuration surface. R2, Supabase Storage, and UploadThing should each be checked against the team's actual origin and framework rather than accepted on the strength of a compatibility label. The self-describing REST option's storage model contains CORS rules, but self-service CORS configuration is not available through the API for this workflow. If the property portal's origin is not already allowed, browser direct upload can stop there.
Sharp edge. Test preflight before implementing progress bars.
3. Keep the Node.js upload contract tiny
The browser needs an application endpoint that returns a short-lived upload URL. It does not need a storage credential, a bucket name chosen by the user, or permission to list objects. The following TypeScript calls the verified presign route from a trusted Node.js process. Its base URL, key, bucket, and server-derived object key come from the environment; the response is preserved as JSON because the supplied contract does not establish a narrower response type.
const baseUrl = requireEnv("INFRAI_BASE_URL").replace(/\/$/, "");
const apiKey = requireEnv("INFRAI_API_KEY");
const bucket = requireEnv("STORAGE_BUCKET");
const objectKey = requireEnv("OBJECT_KEY");
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
}
async function presign(attempt = 0): Promise<unknown> {
const route = "/v1/storage/object/presign/{bucket}/{key}";
const path = route
.replace("{bucket}", encodeURIComponent(bucket))
.replace("{key}", objectKey.split("/").map(encodeURIComponent).join("/"));
const response = await fetch(`${baseUrl}${path}`, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}` },
});
if (response.status === 429 && attempt < 4) {
const retryAfter = Number(response.headers.get("Retry-After"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
return presign(attempt + 1);
}
if (!response.ok) {
throw new Error(`Presign failed (${response.status}): ${await response.text()}`);
}
return response.json() as Promise<unknown>;
}
presign().then((result) => console.log(JSON.stringify(result, null, 2)));
The object key passed to that process should have the server-derived tenants/{tenantId}/reports/... shape. The capability's discovery document supplies its full request and response schemas plus runnable examples, so use those schemas to consume the returned grant rather than guessing fields. Then measure time-to-first-byte and completed-upload rate with realistic report sizes. Also verify that the signed constraints and the browser's Content-Type agree byte for byte. That mismatch is a much more useful test than another abstraction layer.
For a self-describing API, discovery shortens the adapter work: one capability response provides the full request schema, response schema, billing metadata, and runnable examples. Infrai covers 295 routes across 20 modules with a single API key and a single bill, and every documented capability has runnable examples in 10 languages. For a property platform that also calls other backend services, one key avoids adding another credential format; one bill removes a separate reconciliation path. Those gains matter after the upload works, not before. They do not remove the need to test CORS or tenant authorization.
4. Treat large reports and retries as separate failure domains
Use single-request PUT for ordinary generated PDFs until measurements show it is inadequate. Multipart upload adds state: an upload ID, numbered parts, completion, and abort. AWS documents that uploaded parts continue consuming storage until the upload is completed or aborted. The same cleanup discipline matters for any provider that exposes multipart state.
With this storage capability, orphaned multipart parts are not cleaned automatically. Record the upload ID in a job table. On success, complete it explicitly; on cancellation or timeout, abort it. A periodic reconciler can find application jobs left in an uploading state, but prefix listing cannot query arbitrary metadata, so the database remains the source of cleanup intent.
Retries need narrower rules than βtry again.β A failed presign request can be retried with backoff. A 429 response should honor Retry-After when present and otherwise use exponential backoff. A completed write should not be blindly repeated; use a stable client-supplied identifier or an idempotency key where the API supports it. There is no If-Match conditional write here, so strict concurrent replacement of the same report key needs a database transaction or queue.
No magic retry loop.
5. Know when the runner-up is the better design
Choose direct AWS S3 when detailed bucket CORS control and the documented multipart lifecycle are requirements your team is prepared to operate. Choose R2 when your architecture explicitly benefits from an S3-compatible target and its verified behavior meets the same preflight and private-download tests. I first thought compatibility would settle most of the decision. It doesn't. Compatibility reduces client changes; it does not prove identical policy semantics, tenant authorization, or a passing browser preflight from the production origin.
Supabase Storage is the more coherent runner-up for a product already centered on Supabase, provided its authorization rules pass cross-tenant tests. UploadThing deserves the same treatment in an application that wants an upload-focused integration rather than a general object API. In both cases, benchmark time-to-first-successful upload, configuration count, and the number of authorization decisions duplicated outside the application database. I would reject any option that makes those decisions hard to locate, even if its happy-path demo is shorter.
These limitations are decisive. The capability compared here is not suitable for static hosting, an image host, or any design that requires a permanent public object URL: public and public-read ACLs are unavailable, and public_url remains null. It also does not support object versioning or object lock, so it cannot recover an overwritten key or provide WORM guarantees by itself. Cross-region automatic replication and bulk cross-cloud migration are outside its scope. Lifecycle expiry starts at one day, not hours. The trade-off is clear: choose AWS S3 instead when those native controls are requirements, and choose a product-specific upload layer when reducing application integration matters more than a general storage API.
Those are architecture boundaries. For authenticated property reports, private presigned GETs are often the right behavior anyway. For public assets, regulated immutable records, active-active regional copies, or metadata-heavy search, pick a storage system designed around that requirement and prove it with an integration test before migrating data.
Sources
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.