Skip to content

Authenticate against R2 API using auth tokens

The following example shows how to authenticate against R2 using the S3 API and an API token.

Ensure you have set the following environmental variables prior to running either example:

Terminal window
export R2_ACCOUNT_ID=your_account_id
export R2_ACCESS_KEY_ID=your_access_key_id
export R2_SECRET_ACCESS_KEY=your_secret_access_key
export R2_BUCKET_NAME=your_bucket_name

Install the aws-sdk package for the S3 API:

Terminal window
npm install aws-sdk
const AWS = require('aws-sdk');
const crypto = require('crypto');
const ACCOUNT_ID = process.env.R2_ACCOUNT_ID;
const ACCESS_KEY_ID = process.env.R2_ACCESS_KEY_ID;
const SECRET_ACCESS_KEY = process.env.R2_SECRET_ACCESS_KEY;
const BUCKET_NAME = process.env.R2_BUCKET_NAME;
// Hash the secret access key
const hashedSecretKey = crypto.createHash('sha256').update(SECRET_ACCESS_KEY).digest('hex');
// Configure the S3 client for Cloudflare R2
const s3Client = new AWS.S3({
endpoint: `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`,
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: hashedSecretKey,
signatureVersion: 'v4',
region: 'auto' // Cloudflare R2 doesn't use regions, but this is required by the SDK
});
// Specify the object key
const objectKey = '2024/08/02/ingested_0001.parquet';
// Function to fetch the object
async function fetchObject() {
try {
const params = {
Bucket: BUCKET_NAME,
Key: objectKey
};
const data = await s3Client.getObject(params).promise();
console.log('Successfully fetched the object');
// Process the data as needed
// For example, to get the content as a Buffer:
// const content = data.Body;
// Or to save the file (requires 'fs' module):
// const fs = require('fs').promises;
// await fs.writeFile('ingested_0001.parquet', data.Body);
} catch (error) {
console.error('Failed to fetch the object:', error);
}
}
fetchObject();