Using Cloudflare R2 Object Storage to Serve a Comments Field

This application demonstrates integration of Cloudflare’s R2 Object Storage to serve a comments field.

Getting Started

Prerequisites

  • Node.js 20.0.0 or higher

  • npm

  • Cloudflare account

Comments Test Installation

  1. Clone the repository

  2. Install dependencies:

npm install

Create an R2 Bucket, Set CORS Policy, Initialize Empty JSON

  1. Create a Standard Class R2 Bucket in Cloudflare

  2. Add a custom domain for public access (if desired). Skip this to restrict public access to data.

  3. Edit the CORS policy:

    [
      {
        "AllowedOrigins": [
          "*"
        ],
        "AllowedMethods": [
          "GET",
          "PUT",
          "POST",
          "DELETE"
        ],
        "AllowedHeaders": [
          "*"
        ],
        "ExposeHeaders": [
          "Content-Type",
          "Content-Length"
        ],
        "MaxAgeSeconds": 3600
      }
    ]
    
    1. Upload an empty JSON file (comments.json) to the bucket to initialize the comments array

      # comments.json
      
      []
      

Cloudflare Worker: Set Variables, Bindings, and Deploy

  1. For local development, insert your R2 authentication key into .dev.vars.example

  2. Rename it to .dev.vars (check .gitignore for .dev.vars)

    # Rename this file from .dev.vars.example to .dev.vars and 
    # paste in your credentials
    
    AUTH_KEY_SECRET=ENTER_R2_AUTH_KEY
    
  3. In r2-worker.js, replace R2_BUCKET with your specific bucket variable:

    /* ... worker.js code 
    */
    if (!hasValidHeader(request, env)) {
            return createResponse({ error: 'Forbidden' }, 403);
          }
      
          try {
            const bucket = env.INSERT_YOUR_BUCKET_VARIABLE;
            
            switch (request.method) {
    
    /* ... rest of worker.js */
    
  4. Deploy r2-worker.js on Cloudflare under your account.

  5. For live production, set your R2 authentication key as an environment variable or secret as AUTH_KEY_SECRET for the Worker.

  6. Bind your Worker to the R2 Bucket.

In the end, your settings should look something like this:

Worker Settings:

R2 Binding:

Set Your Page Environment Variables

  1. In your Cloudflare Pages settings, set an environment variable or secret, AUTH_KEY_SECRET to your R2 authentication key.

OR

  1. Edit wrangler.toml to include your authentication key:

    #:schema node_modules/wrangler/config-schema.json
    
    name = "comments-r2" // CHANGE TO YOUR PAGES PROJECT NAME
    
    compatibility_date = "2024-12-30"
    pages_build_output_dir = "./build/client"
    
    ######## PRODUCTION environment config ########
    
    # [env.production.vars]
    # AUTH_KEY_SECRET = "ENTER_AUTH_KEY_HERE"
    

Set Worker and R2 URLs in paths.json

  1. Insert the paths to your comments.json file through the Worker:

    {
      "worker_url": "INSERT_WORKER_URL/comments.json"
    }
    

Development

Run the dev server:

npm run dev

To run Wrangler:

npm run build
npm run start

Typegen

Generate types for your Cloudflare bindings in wrangler.toml:

npm run typegen

You will need to rerun typegen whenever you make changes to wrangler.toml.

Deployment

First, build your app for production:

npm run build

Then, deploy your app to Cloudflare Pages:

npm run deploy

Styling

This template comes with Tailwind CSS already configured for a simple default starting experience. You can use whatever css framework you prefer. See the Vite docs on css for more information.

Comments Implementation

After following the initial setup as described above, you can include any type of fields you want, protect comments behind a login, and/or CAPTCHA.

Questions/Issues

I welcome pull requests and issues. You can also contact me directly.

Updated on