Server SDK(Node.js)
Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1>, <APPBASE_CONSOLE_ORIGIN>, and <APPBASE_CONSOLE_HOST> where used with values for the intended environment, and verify that the project and credentials belong to that environment.
Node backends / Workers / CLIs / automation scripts call the Server SDK (agentbase-node-sdk) with a project API Key. The API Key is authorized with the minimum scope, and requests skip row-level permission checks (hasRole) — it can manage data across the entire database, so it must exist only on controlled servers, never in browsers/clients/Sites frontends. For the Java / Python / Go surfaces see java.md / python.md / go.md in the same directory; browser frontends use the Client SDK; governance automation uses the Console SDK.
Installation and initialization
npm install agentbase-node-sdk@2.12.0 --save-exactimport { Client, TablesDB } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint('<APPBASE_ENDPOINT_WITH_V1>') // SIT: https://appbuild-sit.oceanbase.com/v1
.setProject('<PROJECT_ID>')
.setKey(process.env.APPBASE_API_KEY); // Controlled server environment variable
{
const prepareRequest = client.prepareRequest.bind(client);
client.prepareRequest = (...args) => {
const request = prepareRequest(...args);
request.options.redirect = 'error';
return request;
};
}
const tablesDB = new TablesDB(client); // Construct services one by oneEnvironment variable convention: APPWRITE_ENDPOINT / APPWRITE_PROJECT_ID / APPWRITE_API_KEY (+ dotenv); add .setSelfSigned(true) for self-signed instances. Security baseline: row filter conditions must be generated on the server; never trust queries passed in from the frontend.
This configuration is for the pinned Node SDK 2.12 and rejects automatic redirects for normal, streaming, and chunked upload requests that use prepareRequest. It does not cover callRaw, which bypasses that method. Revalidate when changing SDK versions or using other request paths; do not assume every method is protected.
5-minute quickstart
Initialize (see above); create the API Key in the project under Overview → API keys, choosing the minimum scope as needed.
Create a table and write a row:
import { ID } from 'agentbase-node-sdk';
await tablesDB.createTable({
databaseId: 'app-db', tableId: 'tasks', name: 'Tasks',
rowSecurity: true,
columns: [{ key: 'title', type: 'varchar', size: 256, required: true }],
});
await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '写周报' });Issue a login token for a frontend user:
users.createToken('<userId>')→ clientaccount.createSession({ userId, secret })(see the next section).
Custom Token issuance entry points
Server side:
users.createToken('<userId>')→ returns{ secret, expire }.Client (client-sdk/web.md): complete Custom Token login with
account.createSession({ userId, secret }).
Note the distinction: the Tokens service issues Storage file temporary tokens (createFileToken) and is unrelated to user tokens; users.createJWT / account.createJWT issue short-lived JWTs (about 15 minutes) to users for service-to-service calls carrying user identity, not Session channels.
Complete reference of client initialization and auth methods
The Client instance carries connection configuration and request header assembly; all service classes (new TablesDB(client), new KnowledgeBases(client), etc.) can share the same Client instance:
Client Method | Injected HTTP header | Use cases and security constraints |
|---|---|---|
setEndpoint(url) | — (request base URL) | Required, in the form https://appbuild-sit.oceanbase.com/v1 or https://appbuild.oceanbase.com/v1. |
setProject(projectId) | X-Appwrite-Project | Required; specifies the target project ID (e.g. demo project enterprise-ai-hub-210). |
setKey(apiKey) | X-Appwrite-Key | Primary server-side auth method; skips RLS (hasRole) and is constrained by the selected scopes[]. |
setJWT(jwt) | X-Appwrite-JWT | Server-side calls to data plane APIs on behalf of a specific logged-in user (subject to that user's RLS row-level permissions, valid for about 15 minutes). |
setSession(session) | X-Appwrite-Session | Server-side SSR (e.g. Next.js / SvelteKit) loads the user session when forwarding browser session cookies. |
setLocale(locale) | X-Appwrite-Locale | Specifies the internationalization response language (e.g. zh-CN, en-US, ja-JP). |
setSelfSigned(true) | — (TLS verification switch) | For private test instances with self-signed certificates only; strictly forbidden to enable in production. |
addHeader(key, val) | Custom request header | Injects tracing headers (e.g. traceparent) or gateway custom idempotency headers. |
Cursor pagination, file upload, and streaming download patterns
When handling large table traversal, rich document upload, and source file download in production, follow these standard patterns:
import { Client, TablesDB, Storage, Query, ID, AgentbaseException } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
import { writeFileSync } from 'node:fs';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? '<APPBASE_ENDPOINT_WITH_V1>')
.setProject(process.env.APPBASE_PROJECT_ID ?? '<APPBASE_PROJECT_ID>')
.setKey(process.env.APPBASE_API_KEY!);
{
const prepareRequest = client.prepareRequest.bind(client);
client.prepareRequest = (...args) => {
const request = prepareRequest(...args);
request.options.redirect = 'error';
return request;
};
}
const tablesDB = new TablesDB(client);
const storage = new Storage(client);
// 1. Traverse large tables with cursor pagination (prefer Query.cursorAfter over large offsets to avoid deep-pagination performance degradation)
async function iterateAllTickets() {
let lastId: string | null = null;
const pageSize = 100;
while (true) {
const queries = [
Query.equal('status', ['open', 'in_progress']),
Query.orderAsc('$id'),
Query.limit(pageSize),
];
if (lastId) {
queries.push(Query.cursorAfter(lastId));
}
const page = await tablesDB.listRows({
databaseId: 'enterprise_biz_db',
tableId: 'customer_tickets',
queries,
total: false, // Disable count(*) counting to significantly reduce large-table query overhead
});
for (const row of page.rows) {
console.log('处理工单:', row.$id, row.title);
}
if (page.rows.length < pageSize) break;
lastId = page.rows[page.rows.length - 1].$id;
}
}
// 2. Upload local files or in-memory Buffers to a Storage bucket (e.g., the knowledge base source file bucket kb_enterprise_docs)
async function uploadSopDocument() {
const file = await storage.createFile({
bucketId: 'kb_enterprise_docs',
fileId: ID.unique(),
file: InputFile.fromPlainText(
'# 智能客服 SOP 标准作业手册\n1. 首响时效不超过 30 秒...',
'智能客服SOP标准作业手册.md'
),
});
// Download the file's binary byte stream (returns ArrayBuffer)
const bytes = await storage.getFileDownload({
bucketId: 'kb_enterprise_docs',
fileId: file.$id,
});
writeFileSync('/tmp/sop-downloaded.md', Buffer.from(bytes));
}Production-grade error handling and exponential backoff retries
All SDK call exceptions are uniformly thrown as AgentbaseException, containing code (HTTP status code), type (platform error code string, e.g. row_already_exists, rate_limit_exceeded, project_database_read_only), and response (raw response text):
import { AgentbaseException } from 'agentbase-node-sdk';
export async function withRetry<T>(fn: () => Promise<T>, maxAttempts = 3): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
if (err instanceof AgentbaseException) {
// 400 / 401 / 403 / 404 / 409 are deterministic business or permission errors; throw directly without retrying
const retryable = err.code === 429 || err.code === 502 || err.code === 503 || err.code === 504;
if (!retryable || attempt === maxAttempts) {
throw err;
}
const delayMs = Math.min(1000 * 2 ** (attempt - 1), 8000);
await new Promise((r) => setTimeout(r, delayMs));
continue;
}
throw err;
}
}
throw new Error('Unreachable');
}Feature surface navigation
| Service | Coverage | Feature documentation |
|---|---|---|
TablesDB | Databases/tables/columns/indexes/row CRUD, transactions, aggregateRows row aggregation, updateColumnComment | ../databases.md |
Databases / DocumentsDB | Legacy document surface (new projects should prefer TablesDB) | ../databases.md |
Storage | Bucket and file CRUD, download/preview/view | ../storage.md |
Functions | Create/deploy (tar upload, VCS, templates, duplicate), execute, variables, runtime and specification queries | ../functions.md |
Sites | Full Sites and deployment surface (build/variables/framework specifications/logs) | ../sites.md |
Users | Full project user lifecycle + createToken + Target/JWT/MFA | ../users.md |
Teams | Teams and members within a project | ../teams.md |
Messaging | Email/Push/SMS、Topic、Subscriber、Provider | ../messaging.md |
Account / Projects / Project | Account quota read/write and project list override; project settings and variables, organization governance queries; project-level quota requires Console SDK or REST | ../limits.md |
Memory / KnowledgeBases | Full data plane for memory / RAG | ../memory.md, ../knowledge-bases.md |
LlmGateway / AiGateway | Model Provider/Key + execution; unified AI data plane control plane | ../llm-gateway.md, ../ai-gateway.md |
Observability / Moderation | Reporting (≤100 per batch, 207) and queries; moderation configuration and logs | ../observability.md, ../moderation.md |
Webhooks / Graphql / Avatars / Locale / Health / Tokens | Cross-cutting services and file temporary tokens | ../misc/webhooks.md |
| —— | No Sql service: SQL goes through the HTTP form or Console SDK (../databases/sql-proxy.md); No Realtime: real-time push is a client-side capability (../realtime.md) |
Using alongside the Console SDK
The Server SDK's service plane already covers the full set of project features, but the following scenarios require the Console SDK:
Console-only operations: creating projects/Teams,
projects.createPlatformplatform registration (project Keys lack theplatforms.*scope), organization and billing,Admin/Backups.Sqlservice: provided only via Console SDK (or via HTTPPOST {endpoint}/sql)./limitsrate-limited endpoints: when no typed wrapper exists, use Console SDKclient.callor REST.Organization-level usage:
organizations.listUsageAggregatesis Console SDK only.
Using both in the same Node process: npm i agentbase-node-sdk@2.12.0 agentbase-console-sdk@2.12.0 --save-exact, each with its own new Client() loading the Key/Session as needed.
Errors and boundaries
AgentbaseException:codeis the HTTP status code,typeis the error type string; 413 (storage over limit), 429 (rate limited), 401/403 (Key/scope) are covered on each feature page.2.6.0 Secure defaults: the Function API Key does not accept query string transmission; external URLs reject localhost/private network/metadata addresses.
For differences in usage/quota read semantics, see limits.md and usage.md.
Example Guide
Full Node call syntax: ../examples/javascript.md