Upload from the browser straight to a private S3 bucket with short-lived presigned URLs issued after an auth check. Generate keys and enforce size limits server-side, check magic bytes, abort stale multipart uploads, and serve files via presigned GET.
Must-have checklist
Must
Check the session and the user's right to attach a file to the target record before signing any URL; take the bucket and key from server code, never from the client.
A presigned URL acts with the permissions of the server credentials that signed it.
Generate object keys on the server from random ids (for example uploads/<userId>/<uuid>); keep the original filename only in the database.
S3 silently replaces an object with the same key, and user filenames collide and leak into URLs.
Expire upload URLs within minutes (for example 5) and download URLs soon after the download should start; issue a fresh URL instead of a long-lived one.
Presigned URLs are bearer tokens that work repeatedly until they expire.
Enforce the size limit server-side: content-length-range in a presigned POST policy, or for PUT and multipart, check sizes with HeadObject or ListParts before accepting.
A presigned PUT URL alone cannot limit the upload size.
Treat the client's Content-Type and extension as hints; after upload, read the first bytes and match the file signature against an allowlist before marking the file ready.
Both the extension and the Content-Type header are set by the client.
Keep the bucket private with all four Block Public Access settings on and ACLs disabled (Bucket owner enforced); serve private files only through short-lived presigned GET URLs.
Never serve user-uploaded HTML or SVG inline from your app's origin; serve downloads with Content-Disposition: attachment from the storage or a separate CDN domain.
Inline HTML or SVG on your origin runs its scripts as your app (stored XSS).
Limit bucket CORS to your exact app origins and the methods you use (PUT or POST to upload, GET to download); expose ETag if the browser runs multipart uploads.
Send file bytes from the browser straight to S3; use Server Actions and Route Handlers only to sign URLs and confirm uploads.
Server Actions accept 1 MB bodies by default, and serverless hosts cap request bodies.
Add a lifecycle rule that aborts incomplete multipart uploads (for example after 7 days), and a job that deletes objects whose rows stay pending (for example after 24 hours).
Parts of unfinished multipart uploads are billed until the upload is completed or aborted.
Store a row per file (owner, key, original name, size, detected type, status); insert it as pending before signing and mark it ready only after the server checks pass.
Should
Scan files that other users or staff will open for malware, and keep them unavailable until the scan passes.
Sign URLs with an IAM role limited to the upload prefix and to s3:PutObject and s3:GetObject; prefer short-lived role credentials over long-lived access keys.
A presigned URL can do only what its signer is allowed to do.
Use multipart upload with presigned part URLs for files over about 100 MB, uploading parts in parallel and retrying only the failed parts.
A single PUT is capped at 5 GB, and AWS suggests multipart from about 100 MB.
Check size and type in the browser before requesting a URL, show progress, and let users cancel and retry failed uploads.
Decisions to make
Asked before building01How large can a single uploaded file be?
02Which file types will you accept?
03Who should be able to download an uploaded file?
04Where will the files be stored?
Options
4 comparedPresigned direct-to-S3 uploads (POST, PUT or multipart)
- You use Amazon S3 and want file bytes never to pass through your servers
- You need large files or many concurrent uploads
- You want to own storage, keys and access rules in your AWS account
- You need an upload widget, image transforms and scanning with no backend work
- You own CORS, lifecycle rules, validation and cleanup jobs
- Browser multipart uploads need more client code
Presigned uploads to an S3-compatible provider
Examples, not endorsements: Cloudflare R2, Backblaze B2, MinIO
- Download (egress) cost dominates your storage bill
- You self-host storage or need a specific provider or region
- You rely on S3 features your provider lacks, such as POST policies, event notifications or native malware scanning
- Feature support varies; check presigned POST, CORS, lifecycle rules and checksum support
- The SDK client needs a custom endpoint and sometimes path-style addressing
Managed upload service
Examples, not endorsements: UploadThing, Uploadcare, Cloudinary, Vercel Blob
- You want upload UI, resumable uploads and image transforms out of the box
- A small team does not want to own storage security
- Per-GB or per-upload pricing hurts at your expected volume
- Files must stay in your own cloud account
- Vendor lock-in for file URLs and SDKs
- You still authorize uploads and keep file metadata in your database
Proxy uploads through a Server Action or Route Handler
- Files are small (under the 1 MB Server Action default) and must be transformed before storage
- Files can exceed your host's request body limit (for example 4.5 MB on Vercel Functions)
- Uploads are large or frequent
- Every byte costs server bandwidth, memory and function time
- Raising bodySizeLimit widens the denial-of-service surface
Why this approach
Presigned URLs let the browser send file bytes straight to S3, so your Next.js server only authorizes the upload, picks the object key and records metadata; it never buffers files or runs into the 1 MB Server Action limit or a host's request size cap. The bucket stays private, and every upload or download is a short-lived grant for one object that you issue after an auth check. Prefer a presigned POST when S3 itself must enforce a size range; use presigned PUT or multipart for large files and check the size after upload. Choose an S3-compatible provider when egress cost dominates, a managed upload service when you want widgets and transforms without backend work, and server proxying only for small files you must transform first.
Lenses
Authorize first: check the session and the user's right to attach a file to the target record in the Server Action or Route Handler that signs the URL, and rate-limit it per user. Generate the key on the server, sign one operation for one key, and keep expiry short, because a presigned URL works for anyone who holds it until it expires. Sign with an IAM role scoped to the upload prefix. The client's Content-Type and extension are claims, not facts: after upload, read the first bytes with a ranged GetObject, match the file signature against your allowlist, and re-encode images you display. Keep all four Block Public Access settings on and ACLs disabled. Never stream user-uploaded HTML or SVG inline through a Route Handler on your app's domain; that turns an upload into stored XSS. Set response-content-disposition on presigned GETs for anything that isn't a safe image type. Scan files that other people will open, and hide them until the scan passes.
Version notes
- Server Action request bodies are capped at 1 MB by default (
experimental.serverActions.bodySizeLimit); send file bytes to S3, not to an action. proxy.tsbuffers request bodies only up toexperimental.proxyClientMaxBodySize(default 10 MB, renamed frommiddlewareClientMaxBodySize); larger bodies arrive truncated, and Next.js only logs a warning.next/imagekeeps optimized images for at leastimages.minimumCacheTTL(4 hours by default in v16) with no invalidation; don't optimize presigned URLs of private files.- Restrict
images.remotePatternsto your bucket or CDN host and path; the optimizer rejects SVG unlessdangerouslyAllowSVGis set.
- Use the modular v3 clients (
S3Clientplusclient.send(command)); the v2aws-sdkpackage reached end of support in September 2025. - Since about 3.729.0 the client adds CRC32 checksums by default (
requestChecksumCalculation: 'WHEN_SUPPORTED'); if presigned PUTs or an S3-compatible provider fail, set'WHEN_REQUIRED'. - Current 3.x releases require Node.js 20 or later.
- For S3-compatible providers set
endpoint, andforcePathStyle: trueif the provider needs path-style URLs.
getSignedUrl(client, command, { expiresIn })defaults to 900 seconds; SigV4 URLs last at most 7 days and die early if the signing credentials expire.- Content-Type is not signed by default; pass
signableHeaders: new Set(['content-type'])so the browser must send the type you approved. - To sign
x-amz-*headers (for example a checksum), list them inunhoistableHeaders; the browser must then send them. - A presigned PUT cannot enforce a size range; check the size after upload, or use a presigned POST.
createPresignedPostreturns{ url, fields }; the browser posts every field, then the file as the last form field.- Add
['content-length-range', min, max]toConditionsso S3 rejects files outside the range. - Values required by
Conditions(for exampleContent-Type) must also be set inFields; the SDK does not copy them. Expiresdefaults to 3600 seconds; set a few minutes instead.
Verify checks
Requesting an upload URL without a session, or for a record the user cannot edit, returns 401/403 and no URL.
The generated object key contains no part of the client's filename and differs on every call, even for the same filename.
A file one byte over the limit is rejected by S3 (POST policy) or by the confirm step, which deletes the object; the file never becomes ready.
A file named photo.png sent with Content-Type image/png but containing HTML is rejected at the confirm step.
An unsigned request for an object returns 403, and the bucket has all four Block Public Access settings on and ACLs disabled.
Upload and download URLs return 403 after their expiry time.
A browser upload from the app origin succeeds, and the CORS preflight from an unlisted origin fails.
Presigned download URLs for non-image files return Content-Disposition: attachment.
No request to the Next.js app during an upload carries the file bytes; each is a few KB at most.
The bucket lifecycle configuration contains an AbortIncompleteMultipartUpload rule.
An upload that is never confirmed has its row and object removed by the cleanup job after the configured age.
Common mistakes
- Sending file bytes through a Server Action or Route Handler and raising
bodySizeLimituntil large files fit. - Using the user's filename as the object key, which overwrites other files and leaks names into URLs.
- Issuing presigned URLs without checking who is asking or which record the file belongs to.
- Trusting
file.typeor the extension instead of checking the file signature after upload. - A presigned PUT with no size check, so a "10 MB avatar" endpoint accepts a 5 GB file.
- Making the bucket public "just to show images", or presigned URLs that last for days.
- CORS that allows every origin and method, or omits
ETagfromExposeHeaderswhen the browser runs multipart uploads. - Serving uploaded SVG or HTML inline from the app's own domain.
- No lifecycle rule for incomplete multipart uploads and no cleanup of unconfirmed uploads.
- Marking a file ready because the client says the upload finished, without a server-side HeadObject check.