Skip to main 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.

Note

For providing secure access to bucket objects for anonymous users, we recommend using pre-signed URLs instead.

Pre-signed URLs do not require users to be a member of your organization and enable direct programmatic access to R2.

Ensure you have set the following environment variables prior to running either example. Refer to Authentication for more information.

export AWS_REGION=auto
export AWS_ENDPOINT_URL=https://<account_id>.r2.cloudflarestorage.com
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key

JavaScriptPythonGo

Install the @aws-sdk/client-s3 package for the S3 API:

npmyarnpnpmbun

npm i @aws-sdk/client-s3

Run the following Node.js script with node index.js. Ensure you change Bucket to the name of your bucket, and Key to point to an existing file in your R2 bucket.

Note, tutorial below should function for TypeScript as well.

index.js
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";

const s3 = new S3Client();

const Bucket = "<YOUR_BUCKET_NAME>";
const Key = "pfp.jpg";

const object = await s3.send(
  new GetObjectCommand({
    Bucket,
    Key,
  }),
);

console.log("Successfully fetched the object", object.$metadata);

// 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):
// import { writeFile } from "node:fs/promises";
// await writeFile('ingested_0001.parquet', data.Body);