> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloudflare R2

> Set up Cloudflare R2 as a MIRAGE VFS from Node or the browser.

R2 uses the S3 API with AWS Signature V4 against `https://<account-id>.r2.cloudflarestorage.com`. MIRAGE derives this endpoint from your account ID automatically.

Credentials (R2 API token with object read/write scopes) are created the same way in both runtimes, see [R2 Credentials](https://docs.mirage.strukto.ai/home/setup/r2.md).

## Node (server-side)

```bash theme={null}
pnpm add @struktoai/mirage-node
```

```ts theme={null}
import { MountMode, R2VFS, Workspace } from '@struktoai/mirage-node'

const r2 = new R2VFS({
  bucket: process.env.R2_BUCKET!,
  accountId: process.env.R2_ACCOUNT_ID!,
  accessKeyId: process.env.R2_ACCESS_KEY_ID!,
  secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
})

const ws = new Workspace({ '/bucket/': r2 }, { mode: MountMode.READ })
const res = await ws.shell('ls /bucket/')
console.log(res.stdoutText)
```

### Config

| Field | Description |
| - | - |
| `bucket` required | Name of the bucket to mount. |
| `accessKeyId` secret | Access key ID; set it with `secretAccessKey`. Unset uses the AWS SDK credential chain. |
| `secretAccessKey` secret | Secret access key paired with `accessKeyId`. |
| `sessionToken` secret | Session token for temporary credentials, sent with the access key pair. |
| `profile` | Named profile in the shared AWS config and credentials files that supplies credentials when no access key pair is given. |
| `forcePathStyle` | Address the bucket in the URL path (`<endpoint>/<bucket>/<key>`) instead of as a subdomain of the endpoint. |
| `keyPrefix` | Key prefix inside the bucket that the mount treats as its root; keys outside it are not visible. Leading slashes are dropped and a trailing `/` is added. |
| `timeout` default `DEFAULT_TIMEOUT` | Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off. |
| `proxy` secret | Proxy URL for every HTTP and HTTPS request to the endpoint. |
| `region` default `'auto'` | Region requests are signed for; R2 addresses a bucket by account, not by region. |
| `endpoint` | Endpoint URL that replaces the one the provider derives. |
| `accountId` | Cloudflare account ID. It builds the endpoint `https://<accountId>.r2.cloudflarestorage.com` unless `endpoint` is set; one of the two is required. |

Fields marked secret are redacted in snapshots.

## Browser (presigned URLs)

```bash theme={null}
pnpm add @struktoai/mirage-browser
```

The browser `R2VFS` is secret-free, your backend signs each operation using your R2 keys and returns a URL. R2 accepts AWS Signature V4, so `@aws-sdk/s3-request-presigner` works with `region: 'auto'` pointed at R2's endpoint.

### Config

| Field | Description |
| - | - |
| `bucket` required | Name of the bucket to mount. |
| `presignedUrlProvider` required, secret | Function `(path, operation, options)` that returns a signed URL for each S3 operation; your server signs it, so the browser holds no keys. |
| `region` default `'auto'` | Region of the bucket; R2 addresses a bucket by account, not by region. |
| `endpoint` | Endpoint URL that replaces the one the provider derives. Requests go to the host each presigned URL names; the mount uses it to name its storage location. |
| `defaultContentType` default `'application/octet-stream'` | `Content-Type` stored with every object the mount writes. |
| `keyPrefix` | Key prefix the mount treats as its root. The browser can change it before a URL is signed, so enforce the prefix on the signing server. |
| `timeout` default `DEFAULT_TIMEOUT` | Seconds a request may wait to connect, or between two reads of its answer, before it fails; a download that keeps flowing is never cut off. |
| `accountId` | Cloudflare account ID. It builds the endpoint `https://<accountId>.r2.cloudflarestorage.com` unless `endpoint` is set. |

Fields marked secret are redacted in snapshots.

### 1. Server: sign URLs with the R2 endpoint

```ts theme={null}
import {
  CopyObjectCommand,
  DeleteObjectCommand,
  GetObjectCommand,
  HeadObjectCommand,
  ListObjectsV2Command,
  PutObjectCommand,
  S3Client,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'

const client = new S3Client({
  region: 'auto',
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
})
const BUCKET = process.env.R2_BUCKET!

app.post('/presign/r2', async (req, res) => {
  const { path, op, opts } = req.body
  const key = path.replace(/^\/+/, '')
  const ttl = typeof opts?.ttlSec === 'number' ? opts.ttlSec : 300
  let cmd
  switch (op) {
    case 'GET':    cmd = new GetObjectCommand({ Bucket: BUCKET, Key: key }); break
    case 'PUT':    cmd = new PutObjectCommand({ Bucket: BUCKET, Key: key, ContentType: opts?.contentType }); break
    case 'HEAD':   cmd = new HeadObjectCommand({ Bucket: BUCKET, Key: key }); break
    case 'DELETE': cmd = new DeleteObjectCommand({ Bucket: BUCKET, Key: key }); break
    case 'LIST':   cmd = new ListObjectsV2Command({
      Bucket: BUCKET,
      Prefix: opts?.listPrefix,
      Delimiter: opts?.listDelimiter,
      ContinuationToken: opts?.listContinuationToken,
    }); break
    case 'COPY':   cmd = new CopyObjectCommand({
      Bucket: BUCKET,
      Key: key,
      CopySource: `${BUCKET}/${opts?.copySource}`,
    }); break
  }
  res.json({ url: await getSignedUrl(client, cmd, { expiresIn: ttl }) })
})
```

### 2. Browser: wire it up

```ts theme={null}
import { MountMode, R2VFS, Workspace } from '@struktoai/mirage-browser'

const r2 = new R2VFS({
  bucket: 'my-r2-bucket',
  accountId: 'abc123...',
  presignedUrlProvider: async (path, op, opts) => {
    const r = await fetch('/presign/r2', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ path, op, opts }),
    })
    const { url } = await r.json()
    return url
  },
})

const ws = new Workspace({ '/bucket/': r2 }, { mode: MountMode.READ })
```

> [!TIP]
>
> `accountId` on the browser config is only used for display/logging; the actual endpoint is baked into the presigned URLs your backend returns.

### 3. Configure CORS on the bucket

R2 does accept S3-flavored `PutBucketCors`, but your token needs **"Admin Read & Write"** permissions on the bucket, object-scoped tokens will get `Access Denied`. Two paths:

**Option A, Cloudflare Dashboard (fastest, no new token):**

1. Open [https://dash.cloudflare.com](https://dash.cloudflare.com) → **R2** → your bucket
2. **Settings** tab → **CORS Policy** → **Add CORS policy**
3. Origin: `http://localhost:5173` (and any production origins), methods `GET,PUT,HEAD,DELETE,POST`, allowed headers `*`

**Option B, admin-scoped R2 API token + the helper script:**

1. Cloudflare Dashboard → **R2** → **Manage R2 API Tokens** → **Create API token**
2. Permissions: **Admin Read & Write** on your bucket
3. Update `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY` in `.env.development`
4. Run the same helper used for S3:

```bash theme={null}
cd examples/browser
npx tsx scripts/configure-cors.ts http://localhost:5173 https://app.example.com
```

> [!WARNING]
>
> Object-scoped tokens (`Object Read & Write`) cannot edit CORS. If the script returns `Access Denied` on R2, you're almost certainly using an object token.

See the [R2 VFS](https://docs.mirage.strukto.ai/python/vfs/r2.md) docs for the equivalent Python wiring.

For `write: conditional` on this provider, see [S3-compatible stores](https://docs.mirage.strukto.ai/home/configuration.md#s3-compatible-stores).

## VFS.md

The [VFS.md](https://docs.mirage.strukto.ai/home/setup/vfs-md.md) an agent reads with Cloudflare R2 mounted at `/<path>`.

> [tab] Rendered
>
> ### Virtual Filesystem
>
> | Path | Description |
> | - | - |
> | `/<path>` | write |
>
> #### Supported Unix Commands for VFS
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | - | - |
> | `/<path>` | Almost all Unix commands. |
>
> #### Limitations of Unix Commands for VFS
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | - | - |
> | `/<path>` | `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.

> [tab] Raw
>
> ```markdown theme={null}
> ---
> name: workspace-filesystem
> description: The virtual filesystem layout of this workspace.
> ---
>
> # Virtual Filesystem
>
> | Path | Description |
> | --- | --- |
> | `/<path>` | write |
>
> ## Supported Unix Commands for VFS
>
> Unix commands work on each path as on a local filesystem, as far as the path supports them:
>
> | Path | Supported |
> | --- | --- |
> | `/<path>` | Almost all Unix commands. |
>
> ## Limitations of Unix Commands for VFS
>
> Where a path differs from a local filesystem:
>
> | Path | Limitations |
> | --- | --- |
> | `/<path>` | `grep -r`, `find` and `du` stop after 1000 files; a glob matching more, `tar -c`, `cp -r` and `rm -r` are refused. |
>
> Run `man <cmd>` or `<cmd> --help` for one command's usage.
> ```

## Integration

What R2 answers through its own API, so fewer files are read. [Integration](https://docs.mirage.strukto.ai/home/integration/overview.md) explains each command.

| Command | On R2 |
| - | - |
| `md5sum` | The object's ETag, when it is the MD5: a single-part upload, unencrypted or under SSE-S3 |
| `find`, `du`, `ls -R`, `tree` | One recursive listing |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.