or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

examples

edge-cases.mdreal-world-scenarios.md
index.md
tile.json

quick-start.mddocs/guides/

Quick Start Guide

Get started with @cfkit/r2 in minutes. This guide covers installation, basic setup, and common operations.

Installation

npm install @cfkit/r2
# or
pnpm add @cfkit/r2
# or
yarn add @cfkit/r2

Setup

1. Get Cloudflare R2 Credentials

You'll need:

  • Cloudflare Account ID
  • R2 Access Key ID
  • R2 Secret Access Key

Get these from the Cloudflare R2 dashboard.

2. Initialize the Client

import { R2Client } from '@cfkit/r2';

const r2 = new R2Client({
  accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
  accessKeyId: process.env.R2_ACCESS_KEY_ID!,
  secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!
});

3. Get a Bucket Instance

const bucket = r2.bucket('my-bucket-name');

Common Operations

Generate Pre-signed Upload URL

const uploadUrl = await bucket.presignedUploadUrl({
  key: 'photo.jpg',
  contentType: 'image/jpeg',
  expiresIn: 3600 // 1 hour
});

// Client uploads using the URL
await fetch(uploadUrl.url, {
  method: 'PUT',
  headers: { 'Content-Type': 'image/jpeg' },
  body: file
});

Generate Pre-signed Download URL

const downloadUrl = await bucket.presignedDownloadUrl('photo.jpg', {
  expiresIn: 3600
});

// Share downloadUrl.url with users

Upload File Directly (Server-side)

const result = await bucket.uploadFile('photo.jpg', file, {
  contentType: 'image/jpeg',
  metadata: {
    'uploaded-by': 'user-123'
  }
});

console.log(`Uploaded ${result.key} (${result.fileSize} bytes)`);

Download File (Server-side)

const obj = await bucket.getObject('photo.jpg');
const blob = await obj.body.blob();

console.log('File size:', obj.size);
console.log('Content type:', obj.contentType);

Delete File

await bucket.deleteObject('photo.jpg');

Check if Object Exists

const exists = await bucket.objectExists('photo.jpg');
if (exists) {
  // Object exists, proceed with operation
}

Error Handling

Always wrap operations in try-catch blocks:

try {
  await bucket.uploadFile('file.jpg', file, {
    contentType: 'image/jpeg'
  });
} catch (error) {
  if (error instanceof Error) {
    console.error('Upload failed:', error.message);
  }
}

Next Steps

  • See Real-World Scenarios for comprehensive examples
  • Review Edge Cases for advanced scenarios
  • Check the API Reference for complete documentation