AgentDB with JavaScript (Node.js)
Use AgentDB as the database of your JavaScript (Node.js) app. This page shows every call you need, with the built-in fetch of Node.js 22 or newer. No packages.
You can copy each block into your own code. Together they form one program that our tests run.
This page is tested: its code runs locally and in CI against a fresh AgentDB on every change.
Server-side only. This code runs on a server. In a framework such as Express, Fastify, Next.js or Nuxt, put it in server-only code: a route handler, an API route or a server action.
#Before you start
- Node.js 22 or newer. Bun and Deno work the same way.
- A workspace with the example schema:
contact,companyandworks_at. - Three environment variables on your server:
AGENTDB_URL,AGENTDB_API_KEYandAGENTDB_WORKSPACE. See Environment variables.
#Connect
Read the settings from the environment. The key never appears in the code.
const BASE_URL = (process.env.AGENTDB_URL ?? "https://app.agentdb.link").replace(/\/+$/, "");
const API_KEY = process.env.AGENTDB_API_KEY; // a server-side secret: never in browser code
const WORKSPACE = process.env.AGENTDB_WORKSPACE; // ws_...
if (!API_KEY || !WORKSPACE) throw new Error("Set AGENTDB_API_KEY and AGENTDB_WORKSPACE");
const API = `${BASE_URL}/v1/workspaces/${WORKSPACE}`;Every call goes through one small helper. It sends the key in the Authorization: Bearer header, turns AgentDB errors into one error type, and retries when that is safe.
/** An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}. */
class AgentDBError extends Error {
constructor(status, error = {}) {
super(`${status} ${error.code ?? "HTTP_ERROR"}: ${error.message ?? ""}`);
this.status = status;
this.code = error.code ?? "HTTP_ERROR";
this.retryable = error.retryable === true;
this.details = error.details ?? {};
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/**
* One API call. Sends the key in the Authorization header. Retries 429 and 503 with Retry-After
* (or exponential backoff), and network errors when the call is safe to repeat (GET, or a write
* with an Idempotency-Key). Returns the "data" part of the answer, or the raw Response.
*/
async function api(method, path, { json, body, idempotencyKey, raw = false } = {}) {
const headers = { Authorization: `Bearer ${API_KEY}` };
if (json !== undefined) headers["Content-Type"] = "application/json";
if (body !== undefined) headers["Content-Type"] = "application/octet-stream";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const safeToRepeat = method === "GET" || !!idempotencyKey;
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(API + path, { method, headers, body: json !== undefined ? JSON.stringify(json) : body });
} catch (err) {
if (safeToRepeat && attempt < 4) {
await sleep(500 * 2 ** attempt);
continue;
}
throw err;
}
if ((res.status === 429 || res.status === 503) && attempt < 4) {
const retryAfter = Number(res.headers.get("retry-after"));
await sleep(retryAfter > 0 ? retryAfter * 1000 : 500 * 2 ** attempt + Math.random() * 250);
continue;
}
if (!res.ok) {
const envelope = await res.json().catch(() => ({}));
throw new AgentDBError(res.status, envelope.error);
}
return raw ? res : (await res.json()).data;
}
}Check the connection by reading the schema:
const schema = await api("GET", "/object-types");
console.log("Objects:", schema.objects.map((o) => o.name).join(", "));#Create a record
Send the object name and the field values. AgentDB checks each value against its field type. The answer holds the new record with its id and version 1.
const ada = await api("POST", "/records", {
json: { object: "contact", data: { name: "Ada Lovelace", email: `ada-${run}@example.com`, score: 72 } },
idempotencyKey: randomUUID(), // safe to retry: the same key never writes twice
});
console.log("Created", ada.id, "version", ada.version);The Idempotency-Key header makes a retry safe. See Idempotency keys.
#Read a record
const record = await api("GET", `/records/${ada.id}`);
console.log(record.data.name, record.data.email, "version", record.version);#Update a record
An update names the version you read. If someone changed the record since then, AgentDB refuses with VERSION_CONFLICT (HTTP 409) and writes nothing. Read it again, apply your change, and try again:
/** Read, change, write with the current version. On VERSION_CONFLICT: read again and retry. */
async function updateRecord(id, change, attempts = 3) {
for (let i = 1; ; i++) {
const current = await api("GET", `/records/${id}`);
try {
return await api("PATCH", `/records/${id}`, { json: { version: current.version, data: change(current.data) } });
} catch (err) {
if (err instanceof AgentDBError && err.code === "VERSION_CONFLICT" && i < attempts) continue;
throw err;
}
}
}
const updated = await updateRecord(ada.id, (data) => ({ score: data.score + 10 }));
console.log("Score", updated.data.score, "version", updated.version);This is what the conflict looks like:
try {
await api("PATCH", `/records/${ada.id}`, { json: { version: 1, data: { score: 0 } } }); // stale version
} catch (err) {
if (!(err instanceof AgentDBError) || err.code !== "VERSION_CONFLICT") throw err;
console.log("Conflict: the record is now at version", err.details.current_version);
}#Query with filters, sort and pages
A query takes an object, a where filter, a sort and a limit (at most 200). Every condition in all must match. Use the in operator for "one of several values". Operators: eq, neq, in, lt, lte, gt, gte, is_null, is_not_null.
When more records match, the answer holds a next_cursor. Send it as cursor with the same query to get the next page. A next_cursor of null means you have them all.
/** Every record that matches, page by page (limit up to 200; follow next_cursor). */
async function queryAll(object, where, sort, pageSize = 2) {
const out = [];
let cursor = null;
do {
const page = await api("POST", "/query", { json: { object, where, sort, limit: pageSize, ...(cursor && { cursor }) } });
out.push(...page.records);
cursor = page.next_cursor; // null on the last page
} while (cursor);
return out;
}
const good = await queryAll(
"contact",
{ all: [{ field: "score", op: "gte", value: 70 }, { field: "email", op: "neq", value: "nobody@example.com" }] },
[{ field: "score", order: "desc" }],
);
for (const c of good) console.log(c.data.score, c.data.name);See Querying for text search, totals and saved views.
#Link records
A relationship type such as works_at links a contact to a company. Create a link, then list the records on the other side:
const company = await api("POST", "/records", { json: { object: "company", data: { name: `Example Ltd ${run}` } } });
await api("POST", "/links", {
json: { relationship: "works_at", source_record_id: ada.id, target_record_id: company.id },
idempotencyKey: `link-${ada.id}-${company.id}`,
});
const related = await api("GET", `/records/${ada.id}/related?relationship=works_at`);
console.log("Ada works at", related.records.map((r) => r.data.name).join(", "));Add direction=incoming to list from the other side, for example all contacts of a company.
#Files
A file upload has three steps: announce the file with its name, type and size; send the raw bytes; attach it to a record. AgentDB checks that the bytes match the type.
const bytes = Buffer.from(`Meeting notes for Ada (${run})\n`, "utf8");
// 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
const file = await api("POST", "/files", { json: { filename: "notes.txt", content_type: "text/plain", size: bytes.length } });
await api("PUT", `/files/${file.id}/content`, { body: bytes });
await api("POST", "/attachments", { json: { file_id: file.id, record_id: ada.id } });
// Download with the key (server side) ...
const download = await api("GET", `/files/${file.id}/content`, { raw: true });
const back = Buffer.from(await download.arrayBuffer());
// ... or make a signed link that expires, for an <img> or a download button in your page.
const link = await api("POST", `/files/${file.id}/links`, { json: { expires_in_seconds: 600 } });
console.log("Signed link until", link.expires_at);To show a file in a browser, give the page the signed link, never your key. The link expires and can be revoked. See Files and imports.
#Errors
Every error has a stable code, a message, a retryable flag and details, plus an HTTP status. Act on the code.
try {
await api("GET", "/records/rec_doesnotexist");
} catch (err) {
if (!(err instanceof AgentDBError)) throw err; // a network error, not an AgentDB answer
console.log(err.status, err.code, err.message); // 404 NOT_FOUND ...
if (err.retryable) console.log("Safe to retry later");
}fetch throws a TypeError on network errors; the helper retries those only when the call is safe to repeat.
Common codes:
| Code | HTTP | What to do |
|---|---|---|
VALIDATION_ERROR, FIELD_TYPE_MISMATCH | 400 | Fix the request; details names the field. |
UNAUTHENTICATED | 401 | Check the key. |
FORBIDDEN | 403 | The key's role or a permission rule does not allow this. |
NOT_FOUND | 404 | Check the id and the workspace. |
VERSION_CONFLICT | 409 | Read again and retry the update. |
RATE_LIMITED | 429 | Wait for Retry-After, then retry. |
The error codes page lists them all.
#Rate limits and retries
AgentDB limits how many requests a key and a workspace may send. Over the limit, it answers 429 RATE_LIMITED with a Retry-After header in seconds.
The request helper above already handles this:
- On 429 or 503, it waits for
Retry-After, or backs off (0.5, 1, 2, 4 seconds), then tries again. - On a network error, it retries only reads and writes with an idempotency key.
- It gives up after a few attempts and reports the error.
To load many records, use one batch call instead of one call per record: POST /records/upsert takes up to 500 items. See records_upsert_batch.
#Idempotency keys
A timeout can leave you unsure whether a write happened. Send an Idempotency-Key header with each write you may retry. If the same key comes again with the same request, AgentDB returns the first result and writes nothing twice. Keys are kept for 7 days.
const key = randomUUID(); // one key per intention; reuse it only to retry the same request
const request = { object: "contact", data: { name: "Mary Somerville", email: `mary-${run}@example.com` } };
const first = await api("POST", "/records", { json: request, idempotencyKey: key });
const retry = await api("POST", "/records", { json: request, idempotencyKey: key }); // e.g. after a timeout
console.log(first.id === retry.id ? "Same record, written once" : "Duplicate!");Use a new key for each new intention, such as each form submission. The same key with a different request fails with IDEMPOTENCY_KEY_REUSED.
#Run the full example
The complete program is examples/languages/javascript/crm.mjs. Set the three environment variables and run:
node crm.mjsIt prints one OK line per topic: OK connect, OK create, OK read, OK update, OK query, OK relationships, OK files, OK errors and OK idempotency.