Upload files to Cloudflare R2 from Next.js
Send files from the browser straight to an R2 bucket in a Next.js App Router app, with presigned URLs, bucket CORS, type and size limits, and a file size you can trust.
Cloudflare R2 is S3-compatible object storage with no egress fees, which makes it a good home for user uploads. The hard part is getting the file there.
Sending the file through your Next.js server works until it doesn't. On Vercel, a function accepts at most 4.5 MB in its request body, and every byte you pass through costs function time. The usual fix is a presigned URL: your server signs a short-lived URL, and the browser uploads straight to R2.
This guide builds that in a Next.js App Router app with dimah-s3. At the end you have a dropzone that uploads images to R2, a server that picks the object key, and a callback that runs only after R2 has the file.
How it works
- The browser asks your server to upload
photo.pngon theavatarroute. - Your server runs your checks, picks the object key, and signs a PUT URL for R2.
- The browser uploads the file straight to R2.
- Your server reads the stored object with
HeadObjectand runsonConfirmedwith the size and type R2 reports.
Your R2 keys stay on the server the whole time. The browser only ever names a route.
Create the bucket and a token
In the Cloudflare dashboard, open R2 Object Storage and create a bucket. Then create an R2 API token with Object Read & Write permission on that bucket. Copy the access key ID and the secret access key. Cloudflare shows the secret only once.
Your S3 endpoint is https://<ACCOUNT_ID>.r2.cloudflarestorage.com.
Allow your app in bucket CORS
The browser talks to R2 directly, so R2 must allow your app's origin. Add a CORS policy in the bucket's Settings:
[
{
"AllowedOrigins": ["http://localhost:3000", "https://your-app.example"],
"AllowedMethods": ["GET", "PUT", "HEAD"],
"AllowedHeaders": ["*"],
"ExposeHeaders": ["Content-Disposition", "Content-Encoding"],
"MaxAgeSeconds": 3000
}
]Without it, the browser blocks the upload with a CORS error, even though the URL is signed correctly.
Install the packages
You need React 19.2 and Node.js 22 or newer.
npm i @dimah-s3/server @dimah-s3/core @dimah-s3/react @fuma-translate/react @aws-sdk/client-s3Configure the server
S3_ENDPOINT="https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
S3_REGION="auto"
S3_ACCESS_KEY_ID="your-access-key-id"
S3_SECRET_ACCESS_KEY="your-secret-access-key"
S3_BUCKET="your-bucket-name"
# Signs upload tickets. Generate one with: openssl rand -base64 32
DIMAH_S3_SECRET="your-generated-secret"import { S3Client } from "@aws-sdk/client-s3";
import { dimahS3, route } from "@dimah-s3/server";
const r2 = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT,
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
},
// Required: the SDK default (WHEN_SUPPORTED) breaks presigned uploads.
requestChecksumCalculation: "WHEN_REQUIRED",
});
export const s3 = dimahS3({
client: r2,
bucket: process.env.S3_BUCKET!,
routes: {
avatar: route({
upload: {
fileTypes: ["image/*"],
maxFileSize: 2 * 1024 * 1024, // 2 MB
onConfirmed: async ({ key, object }) => {
// object.size comes from R2, not from the browser.
console.log("Stored", key, object.size);
},
},
}),
},
});The route name, avatar, is all the browser can send. It cannot choose the
key, the bucket, or a bigger size limit.
R2 has no presigned POST, so uploads use a presigned PUT. That is the default:
leave upload.method unset.
DIMAH_S3_SECRET must be at least 32 characters and the same on every server
instance. See Upload tickets.
Mount the route handler
import { toNextJsHandler } from "@dimah-s3/server/next";
import { s3 } from "@/lib/s3";
export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(s3);Add the client and the UI
The UI needs Tailwind CSS v4 and shadcn.
npm i @dimah-s3/ui @base-ui/react class-variance-authority cn lucide-react shadcn tw-animate-cssAdd the dimah-s3 styles to your global CSS, after the Tailwind imports:
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@dimah-s3/ui/styles.css"; Create the client, then wrap your app in its provider:
"use client";
import { createS3Client } from "@dimah-s3/react";
export const s3Client = createS3Client();
export const S3Provider = s3Client.Provider;import { Toaster } from "@dimah-s3/ui";
import { S3Provider } from "@/lib/s3-client";
import "./globals.css";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<S3Provider>{children}</S3Provider> {}
<Toaster /> {}
</body>
</html>
);
}Add the dropzone
"use client";
import { useUpload } from "@dimah-s3/react";
import {
Upload,
UploadDropzone,
UploadDropzoneTrigger,
UploadStatus,
} from "@dimah-s3/ui";
export function AvatarUpload() {
const upload = useUpload({ route: "avatar" });
return (
<Upload upload={upload}>
<UploadDropzone>
<UploadDropzoneTrigger />
<UploadStatus />
</UploadDropzone>
</Upload>
);
}Render <AvatarUpload /> on a page and drop an image. The server signs the
upload, the browser sends the file to R2, and your terminal logs the size R2
stored.
Before you ship
- Check who uploads. Add a guard that
reads your session and throws
s3Error("UNAUTHORIZED")when there is none. - Save the key. Store
keyin your database inonConfirmed. It runs at least once per upload, so make the write safe to repeat. - Large files.
upload: { multipart: true }sends big files in parts that upload in parallel and resume after a reload. See Multipart Hooks. - Public files. R2 ignores object ACLs. Connect a custom domain to the
bucket and build URLs from it, as the
R2 guide shows. The
r2.devURL is rate-limited, so keep it for testing. - Private files. Add
download: trueto the route and useuseDownloadfor short-lived signed links.
Or start from a template
The CLI creates a Next.js app with all of this in place. Fill in .env with
your R2 values and run it.
npx @dimah-s3/cli create my-app