Modules
R2 (Storage)

Cloudflare R2 (Object Storage)

What is R2 Storage?

R2 Storage is Cloudflare's cost-effective and scalable object storage solution that allows you to store and serve large files like images, videos, and documents.
It is an alternative to other popular object storage solutions like Amazon S3, Google Cloud Storage, and Vercel Blob(an R2 wrapper) You can learn more about R2 Storage from the official docs (opens in a new tab).

Using R2 Storage in your project

Like other Cloudflare services, R2 has quite a generous free tier, but you must add a payment method to your account before using it. You can click here (opens in a new tab) or manually go to the Cloudflare dashboard and select R2 Storage from the left sidebar.
You will be prompted to enter your payment details, and once you have done that, you can start using R2 Storage for your project.

Creating and Configuring Buckets

Once you have enabled R2 Storage for your account, you can create buckets to store your files. We recommend creating two buckets per project - one for the preview environment and one for the production environment. To create a bucket, follow the onscreen instructions in the Cloudflare dashboard. It is pretty straightforward.
Once done, navigate to the bucket settings and copy the bucket name. You can also connect the bucket to a custom domain on the settings if you want. For example, we have our connected to assets.cloudstarter.com. \

Next, you need to get the access keys. Click here (opens in a new tab) to go to the R2 API Tokens page and create a new token with the following permissions: "Object Read & Write: All". You can choose to restrict to a single bucket or multiple if you wish.

Once you are done, it will show you your Access Key ID and Secret Access Key. Copy these and add them to your project's .dev.vars file as well as in the CF pages settings (opens in a new tab). You will need these to configure the R2 Storage client in your project.

Using R2 Storage in your project

Cloudstarter implements R2 using a presigned URL. This means you can upload directly to the bucket from the client side without going through your server. This is great for performance and security.

The lib/storage.js file contains the logic for generating the presigned URL. You can see its implementation in the api/upload/route.js file.

On the client side, you can look at the components/upload.jsx for implementation on the client side. The component is forked from the Vercel Blob Next.js Starter (opens in a new tab) and reworked to work with R2 storage.

That's it! You have successfully added R2 Storage to your project.
(You are free to implement your own custom logic at this point)