# Upload files to Cloudflare R2 from Next.js (https://s3.dimah.dev/blog/cloudflare-r2-nextjs-uploads)

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 [#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 [#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 [#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**:

```json
[
  {
    "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 [#install-the-packages]

You need React 19.2 and Node.js 22 or newer.

```npm
npm i @dimah-s3/server @dimah-s3/core @dimah-s3/react @fuma-translate/react @aws-sdk/client-s3
```

## Configure the server [#configure-the-server]

```dotenv title=".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"
```

```ts title="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](https://s3.dimah.dev/docs/server/upload-tickets).

## Mount the route handler [#mount-the-route-handler]

```ts title="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 [#add-the-client-and-the-ui]

The UI needs Tailwind CSS v4 and [shadcn](https://ui.shadcn.com/docs/installation).

```npm
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:

```css title="app/globals.css"
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@dimah-s3/ui/styles.css"; /* [!code ++] */
```

Create the client, then wrap your app in its provider:

```ts title="lib/s3-client.ts"
"use client";

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

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

```tsx title="app/layout.tsx"
import { Toaster } from "@dimah-s3/ui"; // [!code ++]
import { S3Provider } from "@/lib/s3-client"; // [!code ++]
import "./globals.css";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <S3Provider>{children}</S3Provider> {/* [!code ++] */}
        <Toaster /> {/* [!code ++] */}
      </body>
    </html>
  );
}
```

## Add the dropzone [#add-the-dropzone]

```tsx title="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 [#before-you-ship]

- **Check who uploads.** Add a [guard](https://s3.dimah.dev/docs/server/hooks/global-guard) that
  reads your session and throws `s3Error("UNAUTHORIZED")` when there is none.
- **Save the key.** Store `key` in your database in
  [`onConfirmed`](https://s3.dimah.dev/docs/server/hooks/upload). 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](https://s3.dimah.dev/docs/server/hooks/multipart).
- **Public files.** R2 ignores object ACLs. Connect a custom domain to the
  bucket and build URLs from it, as the
  [R2 guide](https://s3.dimah.dev/docs/providers/cloudflare-r2#public-files) shows. The `r2.dev` URL
  is rate-limited, so keep it for testing.
- **Private files.** Add `download: true` to the route and use
  [`useDownload`](https://s3.dimah.dev/docs/react/hooks/download) for short-lived signed links.

## Or start from a template [#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.

```npm
npx @dimah-s3/cli create my-app
```

<Cards>
<Card title="Cloudflare R2" href="/docs/providers/cloudflare-r2" description="R2 settings, CORS, and public URLs in the docs." />

<Card title="Quickstart" href="/docs/quickstart" description="The same setup for Hono, Express, and SvelteKit." />

<Card title="Comparison" href="/docs/comparison" description="Choose between dimah-s3, Better Upload, UploadThing, and Uppy." />
</Cards>