Menu

Cloudflare R2 Integration

R2 is an object storage service provided by Cloudflare that seamlessly integrates with Cloudflare's CDN service, serving as a static file storage and distribution solution.

There are many scenarios requiring file storage, for example:

  • User avatar storage
  • AI-generated images and videos saved to the cloud
  • Blog image storage

Once these scenario requirements are identified, administrators also need a file management backend.

The Nexty.dev boilerplate addresses these needs by providing file upload and deletion methods built on Cloudflare R2, along with a backend for viewing and managing files.

In this chapter, we'll complete the Cloudflare R2 configuration.

Configuring Cloudflare R2

  1. Visit the Cloudflare R2 page and start creating a Bucket
Create bucket
Create bucket
  1. Enter Bucket Settings and copy R2_BUCKET_NAME and R2_ACCOUNT_ID to environment variables
Bucket settings
  1. Set up custom domain
Custom domain
Custom domain
  1. Add the configured custom domain with https:// prefix to the environment variable R2_PUBLIC_URL
Custom domain
# .env.local or .env
 
R2_PUBLIC_URL=https://R2_PUBLIC_URL
  1. Configure CORS Policy, which controls which origins (domains, protocols, ports) can access resources stored in the R2 Bucket. This is a security mechanism to protect your resources from unauthorized cross-origin access.
CORS Policy
CORS Policy
[
  {
    "AllowedOrigins": [
      "http://127.0.0.1:3006",
      "http://localhost:3006",
      "https://kontextimage.com",
      "https://flux-kontext.nexty.dev"
    ],
    "AllowedMethods": [
      "GET",
      "PUT",
      "HEAD"
    ],
    "AllowedHeaders": [
      "Content-Type",
      "Content-Length"
    ],
    "ExposeHeaders": [
      "Content-Length",
      "Content-Type",
      "Content-Disposition",
      "ETag",
      "Last-Modified"
    ],
    "MaxAgeSeconds": 3600
  }
]
  1. Now return to the R2 homepage and start creating an API Key
Create API Key
Create API Key
Create API Key
  1. Add the API Key to environment variables R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY
Create API Key

Verification

After starting the source code repository, you can test R2-related functionality in the following modules:

  • /dashboard/settings page to test avatar upload
  • /ai-demo page to test AI-generated image and video upload
  • /dashboard/images page to manage AI Demo generated images and videos