How to Integrate Cloudflare R2 with Ruby on Rails 8 for Public and Private File Storage

Hi all, in this post, you will learn how to configure Cloudflare R2 with Ruby on Rails 8 for efficient file storage. This guide covers both public and private storage setups, Active Storage integration, and best practices for managing your files securely and cost-effectively. Cloudflare offers 10GB of free storage, whereas AWS S3 provides only 5GB.

Integrating Cloudflare R2 with Ruby on Rails 8 can significantly enhance your application’s file storage capabilities, offering both public and private storage solutions. Here’s a comprehensive guide to help you set up and optimize this integration.

Understanding Cloudflare R2

Cloudflare R2 is a robust object storage service that eliminates egress fees, making it a cost-effective alternative to traditional storage solutions. Its compatibility with the S3 API ensures seamless integration with existing tools and frameworks, including Ruby on Rails’ Active Storage.

Setting Up Cloudflare R2 with Rails 8

1. Install Necessary Gems

Begin by adding the required gems to your Gemfile:

gem 'aws-sdk-s3', '~> 1.96'
gem 'dotenv-rails', '~> 2.8', groups: [:development, :test]

After updating the Gemfile, run:

bundle install

2. Configure Active Storage

Modify the config/storage.yml file to include configurations for both public and private storage:

cloudflare_r2_public:
  service: S3
  access_key_id: <%= ENV['CLOUDFLARE_R2_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['CLOUDFLARE_R2_SECRET_ACCESS_KEY'] %>
  region: <%= ENV['CLOUDFLARE_R2_REGION'] %>
  bucket: <%= ENV['CLOUDFLARE_R2_PRIVATE_BUCKET'] %>
  endpoint: <%= ENV['CLOUDFLARE_R2_ENDPOINT'] %>
  public: true
  upload:
    acl: 'public-read'

cloudflare_r2_private:
  service: S3
  access_key_id: <%= ENV['CLOUDFLARE_R2_ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['CLOUDFLARE_R2_SECRET_ACCESS_KEY'] %>
  region: <%= ENV['CLOUDFLARE_R2_REGION'] %>
  bucket: <%= ENV['CLOUDFLARE_R2_BUCKET'] %>
  endpoint: <%= ENV['CLOUDFLARE_R2_ENDPOINT'] %>
  public: false
  upload:
    acl: 'private'

3. Set Environment Variables

Store your sensitive credentials securely using environment variables. You can manage these with a .env file or Rails credentials:

CLOUDFLARE_R2_ACCESS_KEY_ID=your_access_key_id
CLOUDFLARE_R2_SECRET_ACCESS_KEY=your_secret_access_key
CLOUDFLARE_R2_REGION=auto
CLOUDFLARE_R2_PRIVATE_BUCKET=your_private_bucket_name
CLOUDFLARE_R2_BUCKET=your_bucket_name
CLOUDFLARE_R2_ENDPOINT=https://<your-account-id>.r2.cloudflarestorage.com

4. Implement in Rails Models

Define how your models interact with the storage services:

  • Public Files: For assets intended for public access
  • Private Files: For sensitive data requiring restricted access

class Document < ApplicationRecord   
  has_one_attached :file, service: :cloudflare_r2_public 
  has_one_attached :private_file, service: :cloudflare_r2_private
end

5. Uploading and Accessing Files

  • Uploading Files: Attach files to your models as follows:
doc = Document.new 
doc.file.attach(io: File.open('path/to/file'), filename: 'example.txt') 
doc.private_file.attach(io: File.open('path/to/file'), filename: 'private_example.txt') 
doc.save
  • Accessing Public Files: Retrieve the URL using:
 url_for(doc.file)
  • Accessing Private Files: Generate a signed URL for secure access:
Rails.application.routes.url_helpers.rails_blob_url(doc.private_file, only_path: false)

Testing Your Configuration

Ensure everything is set up correctly by:

  • Verifying Access:
    • For public files, check if the URL is accessible without authentication.
    • For private files, confirm that access requires a signed URL.

Benefits of Using Cloudflare R2 Over AWS S3

  • Cost Efficiency: With zero egress fees, you can serve public content without incurring additional costs. Additionally, Cloudflare R2 offers 10GB of free storage, doubling the 5GB provided by AWS S3, making it an even more economical choice for developers.
  • Security: Private storage ensures that sensitive data remains protected, accessible only through authenticated requests.
  • Flexibility: Easily manage both public and private files within the same application, tailoring access based on your application’s requirements.

Here’s a price comparison overview between AWS S3 and Cloudflare R2 from ChatGPT :)

Pricing models for these services often differ significantly in terms of storage, data transfer, and API request costs.

1. Storage Costs

AWS S3$0.023 (up to 50 TB per month)
Cloudflare R2$0.015 per GB
  • Cloudflare R2 is generally cheaper for storage compared to AWS S3.

2. Data Transfer Costs (Egress)

ProviderEgress Pricing
AWS S3$0.09/GB (first 10 TB per month)
Cloudflare R2$0 (Free egress)
  • Cloudflare R2 offers free egress, which can lead to massive savings compared to AWS S3, especially for high data transfer volumes.

3. API Request Costs

Request TypeAWS S3Cloudflare R2
PUT, COPY, POST$0.005 per 1,000 requestsFree
GET, SELECT$0.0004 per 1,000 requestsFree
  • Cloudflare R2 includes free API requests, reducing costs further for frequent operations.

4. Replication and Durability

Both services offer similar durability guarantees of 99.999999999% (11 nines). However:

  • AWS S3 offers additional features like Cross-Region Replication (CRR), which comes at an extra cost.
  • Cloudflare R2 operates with a single-region design but global access optimization to minimize latency.

5. Use Cases

  • AWS S3: Best suited for projects requiring comprehensive AWS ecosystem integration, multi-region replication, or enterprise-level compliance.
  • Cloudflare R2: Ideal for cost-conscious applications or those with significant egress traffic (e.g., hosting public files, content delivery, backups).

Key Takeaways:

  • Cloudflare R2 is more cost-effective for storage and data transfer, especially for projects with high egress traffic or API request volumes.
  • AWS S3 provides more features and integrations but at a higher price point.

Conclusion

By integrating Cloudflare R2 with Ruby on Rails 8, you unlock a seamless, efficient, and cost-effective way to handle your application’s file storage needs. Whether you’re managing public assets or protecting sensitive data, this guide equips you with the tools to set up a robust and scalable solution. As you continue to optimize your application, leveraging Cloudflare R2 will not only reduce costs but also provide the flexibility and security essential for modern web development.

This post is part of the “Mastering Rails 8: Enhancing Your Application Ecosystem” series, where we dive deep into Rails 8’s capabilities and tools to build scalable, efficient, and secure applications. Stay tuned for the next posts in the series, where we’ll explore topics like advanced Active Storage techniques, performance optimization, and much more.

At the core of my philosophy Learn – Develop – Share is the belief that knowledge grows as we explore and build together. Stay tuned as we uncover the endless possibilities of Ruby on Rails, one post at a time!

Leave a Reply

Your email address will not be published. Required fields are marked *