> ## Documentation Index
> Fetch the complete documentation index at: https://dev.writer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Use bindings in Agent Builder v2

> Add a database, object storage, queues, and cron to an Agent Builder v2 Worker, then inspect data in the Data tab.

> [!NOTE]
>
> Agent Builder v2 is in open beta. Features and limitations described here are subject to change.

This guide shows you how to add a database, object storage, queues, and cron jobs to an Agent Builder v2 Worker. After you finish, your app reads those resources from `env`, and you can inspect database tables and stored objects in Control Center.

These features apply to Workers (`index.js`, no root `Dockerfile`). A container does not receive `env.DATABASE` or `env.STORAGE`—use [Vault](https://dev.writer.com/home/agent-builder/getting-started.md#set-vault-secrets) and an external service instead.

| What you can add | How you get it | How you use it |
| - | - | - |
| Database (D1) | WRITER creates it when you deploy a Worker | `env.DATABASE` |
| Object storage (R2) | WRITER creates it when you deploy a Worker | `env.STORAGE` |
| Queue | Declare a producer in root Wrangler config | `env.YOUR_QUEUE` |
| Cron job | Declare schedules under `triggers.crons` in Wrangler | `scheduled` handler |

## Add a database

When you deploy a Worker, WRITER attaches one D1 database for that agent as `env.DATABASE`. Every environment on the agent uses that same database.

1. Deploy a Worker with `index.js` at the archive root and no root `Dockerfile`.
2. Query from `fetch` with prepared statements and `.bind()` for user input:

```javascript theme={null}
export default {
  async fetch(request, env) {
    const { results } = await env.DATABASE.prepare(
      "SELECT id, title, status FROM tickets ORDER BY id DESC LIMIT 20"
    ).all();
    return Response.json({ tickets: results });
  },
};
```

3. Store JSON as `TEXT` with `JSON.stringify` / `JSON.parse` when you need arrays or objects.

For more information, see [Cloudflare's D1 Worker API](https://developers.cloudflare.com/d1/worker-api/).

### Apply database migrations

Put schema files in a **top-level** `migrations/` directory so WRITER applies them at deploy time.

1. Add `*.sql` files such as `0001_init.sql` and `0002_add_status.sql` (lexicographic order).
2. Keep each file safe to run again (`IF NOT EXISTS`, or an `ALTER` that checks whether the change is already there).

```sql theme={null}
CREATE TABLE IF NOT EXISTS tickets (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'open'
);
```

WRITER applies migrations before the Worker serves traffic. A file that fails halfway is not recorded as applied, and the deploy fails. Already-applied files are skipped on later deploys.

> [!NOTE]
>
> SQL that lives only under a nested directory, such as `backend/migrations/`, fails the deploy. Move those files to a top-level `migrations/` directory. Nested SQL next to a real root `migrations/` directory is ignored.

## Add object storage

When you deploy a Worker, WRITER attaches one R2 bucket for that agent as `env.STORAGE`. Every environment on the agent uses that same bucket. Put and get objects from `fetch`. Store the object **key** in the database when you need a file reference, and serve files through your Worker instead of persisting a public URL.

```javascript theme={null}
export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    if (request.method === "PUT" && url.pathname === "/api/files") {
      const key = `uploads/${crypto.randomUUID()}`;
      await env.STORAGE.put(key, request.body);
      return Response.json({ key }, { status: 201 });
    }

    if (request.method === "GET" && url.pathname.startsWith("/api/files/")) {
      const key = url.pathname.replace("/api/files/", "");
      const object = await env.STORAGE.get(key);
      if (!object) {
        return new Response("Not found", { status: 404 });
      }
      return new Response(object.body);
    }

    return new Response("Not found", { status: 404 });
  },
};
```

For more information, see [Cloudflare's R2 Workers API](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/).

## Add a queue

Declare queue producers (and consumers, if you need them) in a root Wrangler config, and omit a root `Dockerfile`. A root Wrangler config that includes queues uses the Wrangler deploy path, which binds only the resources you declare—also declare `DATABASE` and `STORAGE` if your Worker still needs them.

```jsonc theme={null}
{
  "name": "support-agent",
  "main": "index.js",
  "d1_databases": [
    { "binding": "DATABASE", "database_name": "local", "database_id": "local" }
  ],
  "r2_buckets": [
    { "binding": "STORAGE", "bucket_name": "local" }
  ],
  "queues": {
    "producers": [{ "binding": "YOUR_QUEUE", "queue": "tickets" }],
    "consumers": [{ "queue": "tickets" }]
  }
}
```

Send from `fetch`, and handle batches in `queue` when you declare a consumer. This example inserts into the `tickets` table from [Add a database](#add-a-database)—apply that migration first, or the insert fails with `no such table`:

```javascript theme={null}
export default {
  async fetch(request, env) {
    await env.YOUR_QUEUE.send({ title: "Printer jam" });
    return Response.json({ queued: true });
  },
  async queue(batch, env) {
    for (const message of batch.messages) {
      const { title } = message.body;
      await env.DATABASE.prepare(
        "INSERT INTO tickets (title, status) VALUES (?, ?)"
      )
        .bind(title, "open")
        .run();
      message.ack();
    }
  },
};
```

For more information, see [Cloudflare Queues](https://developers.cloudflare.com/queues/configuration/javascript-apis/).

## Add a cron job

Add cron expressions under `triggers.crons` in a root Wrangler config. WRITER applies those schedules on deploy. Handle them in `scheduled`. A config that only declares `triggers.crons` stays on the default Worker path, so `env.DATABASE` and `env.STORAGE` are still attached automatically—you don't need to declare them here:

```jsonc theme={null}
{
  "name": "support-agent",
  "main": "index.js",
  "triggers": {
    "crons": ["0 * * * *"]
  }
}
```

```javascript theme={null}
export default {
  async fetch(request, env) {
    return new Response("ok");
  },
  async scheduled(event, env, ctx) {
    ctx.waitUntil(
      env.DATABASE.prepare(
        "INSERT INTO tickets (title, status) VALUES (?, ?)"
      )
        .bind("Hourly check", "open")
        .run()
    );
  },
};
```

For more information, see [Cloudflare Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/).

## Package and deploy the Worker

Build TypeScript or npm packages locally into `index.js`. The platform does not install packages or compile Worker source. Include `index.js` and, if you use a schema, top-level `migrations/`. Omit a root `Dockerfile`.

```shell theme={null}
COPYFILE_DISABLE=1 tar --exclude='._*' --exclude='node_modules' --exclude='.git' -czvf worker.tar.gz .
```

Upload through Control Center or the WRITER Applications MCP server, as in [Upload and deploy](https://dev.writer.com/home/agent-builder/getting-started.md#upload-and-deploy). You should see the revision move to live.

## Browse database and object storage in the Data tab

After a Worker environment deploys successfully, open that environment in Control Center and select the **Data** tab. You can inspect and edit the same database tables and object-storage folders your Worker uses.

1. Open the agent in Control Center and select the environment (for example **Development**).
2. Select the **Data** tab.
3. Choose a table or a folder in the resource tree to open it in the viewer.

From the **Data** tab you can create and rename tables, edit rows, export table data, upload objects, create top-level folders (prefixes), rename or delete folders, download folder contents, and search. Queues and cron jobs do not appear in this tab.

You should see **Databases** and **Object storage** after the first successful Worker deploy. Rows and files appear after your app or the UI creates them.

![](https://mintcdn.com/writer/QeruaJ61ANItmogG/images/agent-builder/data-tab-database.png?fit=max\&auto=format\&n=QeruaJ61ANItmogG\&q=85\&s=1066cff1f1e50c344bc25931d4f37281)

Uploads through the UI are capped at 25 MB per file. Folders with more than 90 objects cannot be deleted from the **Data** tab—delete those objects from your Worker or reduce the folder size first.

## Match binding names for local development

Keep a root Wrangler config so local `wrangler dev` uses the same names WRITER injects. If the file declares D1 or R2, the binding names must be `DATABASE` and `STORAGE` or the deploy fails. Resource ids in the file are for local use only—WRITER creates the real database and bucket.

```jsonc theme={null}
{
  "name": "support-agent",
  "main": "index.js",
  "d1_databases": [
    { "binding": "DATABASE", "database_name": "local", "database_id": "local" }
  ],
  "r2_buckets": [
    { "binding": "STORAGE", "bucket_name": "local" }
  ],
  "queues": {
    "producers": [{ "binding": "YOUR_QUEUE", "queue": "tickets" }]
  },
  "triggers": {
    "crons": ["0 * * * *"]
  }
}
```

On your own Cloudflare account you would create and bind D1 or R2 in Wrangler yourself; see [Cloudflare Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/). On Agent Builder v2, WRITER attaches the database and object storage for you.

## Troubleshoot bindings

Use this table when a Worker deploy fails on packaging or binding names, or when the **Data** tab has nothing to show after a successful deploy.

| Symptom | What to do |
| - | - |
| `Main module 'index.js' is missing from the Worker bundle` | Add built `index.js` at the archive root, or add a `Dockerfile` only if you intend a container. |
| Deploy fails on D1 or R2 binding names | Use `DATABASE` and `STORAGE` in Wrangler, or remove those sections. |
| `env.DATABASE` or `env.STORAGE` is undefined with a queue Wrangler config | Declare `d1_databases` / `r2_buckets` with those binding names in the same root Wrangler config. A cron-only config doesn't need this—it stays on the default Worker path, which attaches both automatically. |
| `no such table` on the first request | Put `migrations/*.sql` at the archive root and check file name order. |
| Container cannot read `env.DATABASE` or `env.STORAGE` | Use a Worker, or connect the container to an external database with a [Vault secret](https://dev.writer.com/home/agent-builder/getting-started.md#set-vault-secrets). |
| D1 or R2 call fails at module load | Move that I/O into `fetch`. |
| **Data** tab is empty after deploy | Confirm the live revision is a Worker. Create a table or upload an object so the tree has something to show. |
| Cannot delete a folder in the **Data** tab | Folders with more than 90 objects cannot be deleted there. Shrink the folder or delete objects from your Worker. |

## Next steps

* [Get started with Agent Builder v2](https://dev.writer.com/home/agent-builder/getting-started.md) to create an agent, deploy a snapshot, and set Vault secrets.
* [Learn about Agent Builder v2](https://dev.writer.com/home/agent-builder/overview.md) for supported frameworks, environments, and limitations.
* [Call your agent via API](https://dev.writer.com/home/agent-builder/getting-started.md#call-your-agent-via-api) to exercise the endpoints you added.
* [Agent Builder v2 observability](https://dev.writer.com/home/agent-builder/observability.md) to review request performance, events, usage, and logs.
