Get started with @cfkit/r2 in minutes. This guide covers installation, basic setup, and common operations.
npm install @cfkit/r2
# or
pnpm add @cfkit/r2
# or
yarn add @cfkit/r2You'll need:
Get these from the Cloudflare R2 dashboard.
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!
});const bucket = r2.bucket('my-bucket-name');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
});const downloadUrl = await bucket.presignedDownloadUrl('photo.jpg', {
expiresIn: 3600
});
// Share downloadUrl.url with usersconst result = await bucket.uploadFile('photo.jpg', file, {
contentType: 'image/jpeg',
metadata: {
'uploaded-by': 'user-123'
}
});
console.log(`Uploaded ${result.key} (${result.fileSize} bytes)`);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);await bucket.deleteObject('photo.jpg');const exists = await bucket.objectExists('photo.jpg');
if (exists) {
// Object exists, proceed with operation
}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);
}
}