Menu

CloudFlare R2 Integration

R2 is an object storage service provided by CloudFlare that seamlessly integrates with CloudFlare's CDN service and can serve as a static file storage and distribution service.

There are many scenarios that require file storage, for example:

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

With these needs, administrators also require a file management backend.

The Nexty.dev template addresses these requirements by encapsulating file upload and deletion methods based on CloudFlare R2, and provides a backend for viewing and managing files.

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

Configure CloudFlare R2

  1. Visit the CloudFlare R2 page and start creating a Bucket

Create bucket

Create bucket

  1. Go to 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 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 your R2 Bucket. This is a security mechanism to protect your resources from unauthorized cross-origin access.

CORS Policy

CORS Policy

[
  {
    "AllowedOrigins": [
      "http://localhost:3000",
      "https://your-domain.com"
    ],
    "AllowedMethods": [
      "GET"
    ]
  }
]
  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

You can start the source code repository and test R2-related features in the following modules:

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