Skip to content

R2 Buckets

R2 is Cloudflare’s S3-compatible object storage. The integration provides both a hosting side (provision the bucket) and a client side (use it from your app).

builder.AddCloudflareEnvironment();
var uploads = builder.AddR2Bucket("uploads").RunAsEmulator();
  • aspire run → with .RunAsEmulator(), a local MinIO emulator backs the bucket; it’s created automatically. No credentials needed. Without it, aspire run targets real R2 (and provisions the bucket).
  • aspire deploy → the bucket is always provisioned in real R2 via the Cloudflare API (.RunAsEmulator() only affects run mode).

The default is real R2 — calling .RunAsEmulator() opts into the local MinIO loop, mirroring the RunAsEmulator() convention of Aspire’s Azure integrations.

builder.AddR2Bucket("uploads", bucketName: "my-prod-bucket")
.RunAsEmulator() // back with local MinIO during `aspire run` (no credentials)
.WithLocationHint("weur") // R2 location hint
.AllowDeletion(); // permit `aspire destroy` to delete the bucket
builder.AddProject<Projects.Api>("api").WithReference(uploads);

This injects an S3-compatible connection string into the service.

In the consuming project:

builder.AddR2Client("uploads");

This registers an IR2Client (and the underlying IAmazonS3) tuned for R2. IR2Client is bound to the bucket, so you don’t pass the bucket name on every call. The same code works against MinIO locally and real R2 in production:

app.MapPut("/files/{key}", async (string key, Stream body, IR2Client r2) =>
{
await r2.PutObjectAsync(key, body);
return Results.Created($"/files/{key}", null);
});

Need an operation the wrapper doesn’t expose? Use r2.S3 (the underlying IAmazonS3) or inject IAmazonS3 directly.

  • API token (provisioning): needs Workers R2 Storage: Edit — see API Tokens.
  • S3 credentials (runtime data access): R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY — see R2 S3 Credentials.