Documentation

Cloudflare R2 Static Asset Storage

ready

Zero-egress fee object storage for Next.js static chunks, custom user upload buckets (CORS, lifecycle, jurisdiction), and optional native Workers Static Assets.

Source reference: cli/internal/serverless/cloudflare/r2_resources.go, cli/internal/serverless/cloudflare/static_assets.go


Why R2 for Next.js Static Assets?

Next.js compiles static assets (JavaScript bundles, CSS stylesheets, fonts) into .next/static/. Keeping them outside worker.mjs keeps the Worker bundle small and fast to deploy:

  1. During nextdeploy ship, content-hashed /_next/static/* assets are uploaded first with Cache-Control: public, max-age=31536000, immutable.
  2. Mutable .html, .rsc, and public/* objects are uploaded under fingerprinted _nextdeploy/releases/<sha256>/ prefixes so rollbacks resolve matching assets.
  3. NextDeploy automatically prunes older R2 releases beyond the 5 most recent builds to keep storage bounded.
  4. Optionally, set static_assets.mode: workers_assets to serve static files directly via Cloudflare's native Workers Static Assets without invoking the Worker for static hits.

Configuration in nextdeploy.yml

NextDeploy auto-provisions your framework ASSETS R2 bucket automatically. Declare additional custom R2 buckets under resources.r2 with optional binding:, location_hint, jurisdiction, storage_class, cors, lifecycle, public_domain, and protect: true:

version: "1.0"
target_type: serverless

app:
  name: my-app
  domain: app.example.com
  environment: production

serverless:
  provider: cloudflare
  cloudflare:
    compatibility_date: "2026-05-01"
    compatibility_flags:
      - nodejs_compat
    resources:
      r2:
        - name: my-app-uploads
          binding: USER_UPLOADS
          location_hint: weur
          storage_class: Standard
          protect: true
          cors:
            - allowed_origins: ["https://app.example.com"]
              allowed_methods: ["GET", "PUT"]
              max_age_seconds: 3600
          lifecycle:
            - id: cleanup-temp
              prefix: tmp/
              expire_after_days: 7

Direct R2 Bucket Binding in Application Code

Access the R2Bucket binding through globalThis.__nextdeployEnv (run nextdeploy types for typed CloudflareEnv):

// app/api/upload/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function PUT(req: NextRequest) {
  const env = (globalThis as { __nextdeployEnv?: CloudflareEnv }).__nextdeployEnv;
  const bucket = env?.USER_UPLOADS;
  if (!bucket) {
    return NextResponse.json({ error: 'USER_UPLOADS binding not configured' }, { status: 500 });
  }

  const filename = req.headers.get('x-filename') || 'upload.bin';
  const fileBody = await req.arrayBuffer();

  await bucket.put(filename, fileBody, {
    httpMetadata: {
      contentType: req.headers.get('content-type') || 'application/octet-stream',
    },
  });

  return NextResponse.json({ success: true, key: filename });
}

Related