Mustlist

User file uploads for a Next.js app with Amazon S3

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

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.

Forweb-appsaasdashboardmarketplace
Not forstatic-assets-in-the-repofiles-generated-only-on-the-server

Must-have checklist

11 must · 4 should

Must

01

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.

Security
02

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.

Security
03

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.

Security
04

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.

Security
05

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.

Security
06

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.

Security
07

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).

Security
08

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.

Security
09

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.

Performance
10

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.

Cost
11

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.

Data

Should

12

Scan files that other users or staff will open for malware, and keep them unavailable until the scan passes.

Security
13

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.

Security
14

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.

Performance
15

Check size and type in the browser before requesting a URL, show progress, and let users cancel and retry failed uploads.

UX

Decisions to make

Asked before building

01How 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?

05Will other users or your staff open files that someone else uploaded?

Options

4 compared
RecommendedFits your answers

Presigned direct-to-S3 uploads (POST, PUT or multipart)

Best fit when
  • 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
Avoid when
  • You need an upload widget, image transforms and scanning with no backend work
Trade-offs
  • 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

Best fit when
  • Download (egress) cost dominates your storage bill
  • You self-host storage or need a specific provider or region
Avoid when
  • You rely on S3 features your provider lacks, such as POST policies, event notifications or native malware scanning
Trade-offs
  • 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

Best fit when
  • You want upload UI, resumable uploads and image transforms out of the box
  • A small team does not want to own storage security
Avoid when
  • Per-GB or per-upload pricing hurts at your expected volume
  • Files must stay in your own cloud account
Trade-offs
  • 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

Best fit when
  • Files are small (under the 1 MB Server Action default) and must be transformed before storage
Avoid when
  • Files can exceed your host's request body limit (for example 4.5 MB on Vercel Functions)
  • Uploads are large or frequent
Trade-offs
  • 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

next>=16.0.0
  • Server Action request bodies are capped at 1 MB by default (experimental.serverActions.bodySizeLimit); send file bytes to S3, not to an action.
  • proxy.ts buffers request bodies only up to experimental.proxyClientMaxBodySize (default 10 MB, renamed from middlewareClientMaxBodySize); larger bodies arrive truncated, and Next.js only logs a warning.
  • next/image keeps optimized images for at least images.minimumCacheTTL (4 hours by default in v16) with no invalidation; don't optimize presigned URLs of private files.
  • Restrict images.remotePatterns to your bucket or CDN host and path; the optimizer rejects SVG unless dangerouslyAllowSVG is set.
@aws-sdk/client-s3>=3.0.0 <4.0.0
  • Use the modular v3 clients (S3Client plus client.send(command)); the v2 aws-sdk package 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, and forcePathStyle: true if the provider needs path-style URLs.
Official docsContext7docs.aws.amazon.com
@aws-sdk/s3-request-presigner>=3.0.0 <4.0.0
  • 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 in unhoistableHeaders; the browser must then send them.
  • A presigned PUT cannot enforce a size range; check the size after upload, or use a presigned POST.
Official docsContext7docs.aws.amazon.com
@aws-sdk/s3-presigned-post>=3.0.0 <4.0.0
  • createPresignedPost returns { url, fields }; the browser posts every field, then the file as the last form field.
  • Add ['content-length-range', min, max] to Conditions so S3 rejects files outside the range.
  • Values required by Conditions (for example Content-Type) must also be set in Fields; the SDK does not copy them.
  • Expires defaults to 3600 seconds; set a few minutes instead.
Official docsContext7docs.aws.amazon.com

Verify checks

11 checks
01

Requesting an upload URL without a session, or for a record the user cannot edit, returns 401/403 and no URL.

integrationSecurity
02

The generated object key contains no part of the client's filename and differs on every call, even for the same filename.

unitSecurity
03

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.

integrationSecurity
04

A file named photo.png sent with Content-Type image/png but containing HTML is rejected at the confirm step.

integrationSecurity
05

An unsigned request for an object returns 403, and the bucket has all four Block Public Access settings on and ACLs disabled.

manualSecurity
06

Upload and download URLs return 403 after their expiry time.

integrationSecurity
07

A browser upload from the app origin succeeds, and the CORS preflight from an unlisted origin fails.

e2eSecurity
08

Presigned download URLs for non-image files return Content-Disposition: attachment.

integrationSecurity
09

No request to the Next.js app during an upload carries the file bytes; each is a few KB at most.

integrationPerformance
10

The bucket lifecycle configuration contains an AbortIncompleteMultipartUpload rule.

manualCost
11

An upload that is never confirmed has its row and object removed by the cleanup job after the configured age.

integrationData

Common mistakes

  • Sending file bytes through a Server Action or Route Handler and raising bodySizeLimit until 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.type or 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 ETag from ExposeHeaders when 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.

Sources

23 sources