Next.js uploads to S3 or Cloudflare R2
This guide sends files from the browser straight to Amazon S3 or Cloudflare R2
with @uppy/aws-s3. A Next.js App Router route handler signs a
short-lived URL for each file, so the file never passes through your server.
Configure storage
npm install @uppy/core @uppy/aws-s3 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
Set S3_BUCKET to the name of a private bucket, then set the variables for your
provider:
- Amazon S3: set
S3_REGIONto the bucket’s region. LeaveS3_ACCESS_KEY_IDunset so the AWS SDK loads credentials from its default provider chain. - Cloudflare R2: set
S3_REGION=autoandS3_ENDPOINTtohttps://<ACCOUNT_ID>.r2.cloudflarestorage.com. SetS3_ACCESS_KEY_IDandS3_SECRET_ACCESS_KEYto the S3 credentials of an R2 API token scoped to that bucket.
The S3_ prefix keeps these values away from any other AWS SDK client in the
app, since those read the standard AWS_ variables. Don’t prefix them with
NEXT_PUBLIC_, which would expose them to the browser.
Give the credentials the route signs with permission to write only to the target bucket or prefix.
Configure the bucket’s CORS rules to allow
your app’s origin, PUT, and the Content-Type header, and to expose ETag.
Write each origin as scheme, host, and port with no path or trailing slash, for
example http://localhost:3000 in development and your deployed app’s origin in
production. For R2, see
also Cloudflare R2 CORS.
Sign a single PUT on the server
Add the route below at app/api/uploads/presign/route.ts. It assumes your app
already has Auth.js
configured and exports auth from @/auth. With a different auth provider,
use its server-side session helper instead. As written, the route lets
signed-in users upload PNG and JPEG images of up to 10 MiB. Add any narrower
permissions or per-user quotas here.
import { randomUUID } from 'node:crypto'
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { auth } from '@/auth'
const s3 = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT,
credentials: process.env.S3_ACCESS_KEY_ID
? {
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
}
: undefined,
requestChecksumCalculation: 'WHEN_REQUIRED',
})
export async function POST(request: Request) {
if (!(await auth())?.user) {
return Response.json({ error: 'Sign in to upload files' }, { status: 401 })
}
if (request.headers.get('content-type')?.split(';')[0] !== 'application/json') {
return Response.json({ error: 'Expected JSON' }, { status: 415 })
}
const { type, size } = (await request.json().catch(() => null)) ?? {}
if (
(type !== 'image/png' && type !== 'image/jpeg') ||
!Number.isSafeInteger(size) || size < 1 || size > 10 * 1024 * 1024
) {
return Response.json({ error: 'Choose a PNG or JPEG up to 10 MiB' }, { status: 400 })
}
const key = `uploads/${randomUUID()}`
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET,
Key: key,
ContentType: type,
ContentLength: size,
})
const url = await getSignedUrl(s3, command, {
expiresIn: 60,
signableHeaders: new Set(['content-type', 'content-length']),
})
return Response.json({ url, key, headers: { 'content-type': type } })
}
Keep requestChecksumCalculation: 'WHEN_REQUIRED'. Since version 3.729.0,
@aws-sdk/client-s3 adds a CRC32 checksum to every PutObject by default. The
server signs the URL without the file, so that checksum can’t match what the
browser sends, and the upload fails.
The server picks the object key and signs the Content-Type and
Content-Length headers. The route returns only content-type in headers
because the browser sets Content-Length from the file itself. S3 and R2
reject an upload whose type or size differs from what the route signed. The
signature covers the headers but not the bytes, so a client can still upload
other data labeled image/png. If you show uploads to other users or rely on
the real image format, check the file contents on the server first.
Upload from a client component
Render this component on a page that only signed-in users can reach.
signRequest receives the S3 request but not the file, so the component
creates an Uppy instance for each submission and reads the file’s type and size
from the closure. It destroys the instance when the upload ends.
'use client'
import { type FormEvent, useState } from 'react'
import Uppy from '@uppy/core'
import AwsS3 from '@uppy/aws-s3'
export default function UploadForm() {
const [uploading, setUploading] = useState(false)
const [status, setStatus] = useState('')
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const file = new FormData(event.currentTarget).get('file')
if (!(file instanceof File)) return
const uppy = new Uppy().use(AwsS3, {
shouldUseMultipart: false,
async signRequest() {
const response = await fetch('/api/uploads/presign', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: file.type, size: file.size }),
})
const result = await response.json().catch(() => ({}))
if (!response.ok || typeof result.url !== 'string') {
throw new Error(result.error ?? 'Could not sign the upload')
}
return result
},
})
setUploading(true)
setStatus('Uploading…')
try {
uppy.addFile({ data: file, name: file.name, type: file.type })
const result = await uppy.upload()
if (!result?.successful?.length) {
throw new Error(String(result?.failed?.[0]?.error ?? 'Upload failed'))
}
setStatus(`Uploaded ${file.name}`)
} catch (error) {
setStatus(error instanceof Error ? error.message : 'Upload failed')
} finally {
uppy.destroy()
setUploading(false)
}
}
return (
<form onSubmit={onSubmit}>
<label>
Image <input name="file" type="file" accept="image/png,image/jpeg" required />
</label>
<button disabled={uploading}>Upload</button>
<p role="status">{status}</p>
</form>
)
}
Upload an image with the browser’s network tab open. You should see a POST to
/api/uploads/presign and a PUT to the storage hostname, and only the PUT
carries the file. The new object shows up in the bucket under uploads/.
The route returns the object key, and Uppy reports it as response.body.key on
each file in result.successful. Your app needs that key to find the file
later, so send it to your server once the upload succeeds, for example to a
route that checks the session and stores the key with the user’s ID. Storing it
while signing would leave records for uploads that never finished.
This route signs one PutObject request per file. For larger files,
sign the multipart operations or upload
through a Tus server with the Tus uploader.