Dev.to WebDev 🛠 Dev 👁 2 📖 5 min read

Upload files to Cloudflare R2 from Next.js

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'

Upload files to Cloudflare R2 from Next.js

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

  1. The browser asks your server to upload photo.png on the avatar route.
  2. Your server runs your checks, picks the object key, and signs a PUT URL for R2.
  3. The browser uploads the file straight to R2.
  4. Your server reads the stored object with HeadObject and runs onConfirmed with 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-s3

Configure the server

.env

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"

lib/s3.ts

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

app/api/s3/[...s3]/route.ts

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-css

Add the dimah-s3 styles to your global CSS, after the Tailwind imports:

app/globals.css

@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:

lib/s3-client.ts

"use client";

import { createS3Client } from "@dimah-s3/react";

export const s3Client = createS3Client();
export const S3Provider = s3Client.Provider;

app/layout.tsx

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

components/avatar-upload.tsx

"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 key in your database in onConfirmed. 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.dev URL is rate-limited, so keep it for testing.
  • Private files. Add download: true to the route and use useDownload for 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

I maintain dimah-s3, the open-source (MIT) library this guide uses. This guide first appeared on the dimah-s3 blog.

GitHub logo dimah-kz / dimah-s3

Full-stack S3 toolkit for the React ecosystem on your own bucket (S3, R2, MinIO)

dimah-s3

npm version GitHub stars documentation license

S3 file uploads for React and Next.js, on a bucket you own.

Your server signs a short-lived URL, the browser uploads straight to your bucket, and S3 credentials never leave the backend. It works with Amazon S3 Cloudflare R2, MinIO, ArvanCloud, and any other S3-compatible store. You get upload, download, and delete, with headless React hooks and optional shadcn components.

Think of it as an open-source UploadThing that runs on your own storage: no hosted file service in between, and you pay only your storage provider.

The dimah-s3 file browser: folders, files with type icons, storage usage, search, sort, and an Upload files button

Why dimah-s3

  • Your bucket, your keys. The browser sends a route name. Your server picks the object key and runs your auth and quota checks.
  • Verified uploads. The server confirms each upload with HeadObject, so size and type come from S3, not from the browser.
  • The whole lifecycle. Upload, private download, and guarded delete, with multipart uploads that resume after a reload.
  • …




📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.