JavaScript SDK
@namidb/cloud is the official JavaScript and TypeScript client. It runs
Cypher over the HTTP API and wraps the
management API. It has no runtime
dependencies and only needs the global fetch, so it runs on Node 18+,
Deno, Bun, edge runtimes and browsers. Apache-2.0.
npm install @namidb/cloudQuick start
import { NamiDB } from '@namidb/cloud';
const db = new NamiDB(); // reads NAMIDB_API_KEY (and NAMIDB_URL, default https://db.namidb.com)
await db.query('movies', 'CREATE (:Movie {id: $id, title: $title})', { id: 'm1', title: 'Heat' });
const { rows } = await db.query<{ title: string }>( 'movies', 'MATCH (m:Movie) RETURN m.title AS title ORDER BY title LIMIT $n', { n: 10 },);
const movies = db.database('movies'); // bind one databaseconst schema = await movies.schema();new NamiDB(options?)
| Option | Default | |
|---|---|---|
apiKey | process.env.NAMIDB_API_KEY | Required; otherwise the constructor throws missing_api_key |
url | process.env.NAMIDB_URL ?? https://db.namidb.com | |
timeoutMs | 90000 | Per attempt. Covers the longest plan query timeout (60 s) plus a cold start |
maxRetries | 2 | Retries after the first attempt |
fetch | globalThis.fetch | Your own fetch implementation |
Methods
db.query<T>(database, cypher, params?, options?)
Resolves to:
{ columns: string[]; rows: T[]; // one object per row, keyed by column writeOutcome?: { nodesCreated, edgesCreated, nodesDeleted, edgesDeleted, propertiesSet }; requestId: string | null; // quote it to support engineMs: number | null; // time spent in the engine}options: idempotent (see Retries), timeoutMs, and signal
(an AbortSignal that cancels the request and any pending retry).
Values use the engine’s JSON encoding: a node is
{ _kind: 'node', id, label, labels, properties }, a relationship
{ _kind: 'rel', edge_type, src, dst, properties }, datetimes are RFC 3339
strings, bytes base64, vectors number arrays. Integers arrive as JavaScript
numbers: use strings for identifiers beyond Number.MAX_SAFE_INTEGER.
Parameters must be JSON-serializable (no BigInt).
db.schema(database, options?)
{ constraints, indexes, labels, relationshipTypes, requestId }; each
constraint and index is { name, type, entityType, labelsOrTypes, properties }.
db.databases(options?)
The databases the key can reach: [{ name, status }].
db.runningQueries(database, options?) and db.cancelQuery(database, id, options?)
runningQueries resolves to the statements running on the database right
now, longest-running first: [{ id, protocol, statement, elapsedMs }].
cancelQuery stops one of them at its next cancellation check, and its
client gets a cancelled error. Both need a read-write key
(read_only_key otherwise), since statement text includes its literals.
Cancelling a statement that is no longer running throws query_not_found.
import { NamiDB, NamiDBError } from '@namidb/cloud';
for (const q of await db.runningQueries('movies')) { if (q.elapsedMs > 60_000) { await db.cancelQuery('movies', q.id).catch((err) => { if (!(err instanceof NamiDBError && err.code === 'query_not_found')) throw err; }); }}Listing is retried like a read and never wakes a sleeping database (it then has nothing running). A cancel is retried only when NamiDB refused it before it could take effect. Neither counts as a request.
db.database(name)
A handle with query, schema, runningQueries, cancelQuery,
bulkWrite, importNodes and importRelationships bound to that database.
Bulk import
await db.importNodes('movies', people, { label: 'Person', key: 'id', // MERGE on id; other fields become properties onProgress: (p) => console.log(p.rowsDone, p.rowsTotal),});
const res = await db.importRelationships('movies', [{ from: 1, to: 2, since: 2020 }], { type: 'KNOWS', from: { label: 'Person', key: 'id' }, to: { label: 'Person', key: 'id' },}); // res.linked counts rows whose two ends exist
await db.bulkWrite('movies', 'UNWIND $rows AS row MERGE (m:Movie {title: row.title})', titles, { idempotent: true });Batches are cut at batchRows (default 1,000) and batchBytes (default
1 MiB), wait out rate_limited and engine_starting as Retry-After says
(maxRateLimitRetries, default 30), and split in halves on
payload_too_large. MERGE batches are retried like reads; a CREATE
batch is never resent after an ambiguous failure. A failure throws a
NamiDBError that says how many rows went in before it.
Errors
Every failure rejects with a NamiDBError: code, status (0 when no
response arrived), message, requestId, retryAfter (seconds or null),
and neo4jCode / gqlStatus when the engine reported them.
import { NamiDB, NamiDBError } from '@namidb/cloud';
try { await db.query('movies', 'CREATE (:Movie {id: "m1"})');} catch (err) { if (err instanceof NamiDBError && err.code === 'read_only_key') { // this key can only read } else if (err instanceof NamiDBError && err.code === 'plan_limit') { // allowance used up: upgrade, or wait err.retryAfter seconds } else { throw err; }}Every code: Errors. Client-side codes:
request_timeout, connection_error, invalid_response,
invalid_argument, missing_api_key, http_error.
Retries
Up to maxRetries times, waiting for Retry-After when the server sends one
(longer than 60 s is reported instead of waited), else exponential backoff
with jitter from 0.5 s to 8 s.
Writes are never retried once they may have reached the engine. A query
counts as a write when it contains a write clause (CREATE, MERGE, SET,
DELETE, REMOVE, DROP, CALL, …). Writes are still retried when
NamiDB refused them before the engine saw them (engine_starting,
rate_limited, control_plane_unavailable) or when the connection was never
made. Override the check per call:
await db.query('movies', 'MERGE (:Movie {id: $id})', { id: 'm1' }, { idempotent: true }); // safe to repeatawait db.query('movies', 'MATCH (n) RETURN n', {}, { idempotent: false }); // never repeatschema() and databases() are always retried.
Management API
ManagementClient uses a management token (nmdb_mgmt_…) against
https://app.namidb.com/api/v1.
import { ManagementClient } from '@namidb/cloud';
const mgmt = new ManagementClient(); // reads NAMIDB_MANAGEMENT_TOKEN (and NAMIDB_MANAGEMENT_URL)
const db = await mgmt.databases.create('movies');const key = await mgmt.apiKeys.create({ name: 'movies-app', role: 'read-only', databases: ['movies'] });console.log(key.token); // the full API key, returned this once
const backup = await mgmt.backups.create('movies');await mgmt.restores.create({ backupId: backup.id, databaseName: 'movies-copy' });await mgmt.clones.create('movies', { name: 'movies-staging', source: 'fresh_snapshot' });// The database as it was 24 hours ago (exact inside the plan's restore-point window).const pit = await mgmt.restores.pointInTime('movies', { at: new Date(Date.now() - 86_400_000), databaseName: 'movies-yesterday' });// poll mgmt.clones.get(pit.id) until 'succeeded'; then pit.recoveryPoint and pit.recoverySource say what it holds
// A short-lived token for a CI job (needs the admin scope; never broader or longer-lived than this one).const ci = await mgmt.managementTokens.create({ name: 'ci', scope: 'write', expiresAt: new Date(Date.now() + 3_600_000) });console.log(ci.token); // shown this once
const exp = await mgmt.exports.create('movies'); // poll mgmt.exports.get(exp.id) until 'succeeded'const cypher = await mgmt.exports.download(exp.id, 'import.cypher');
await mgmt.ipAllowlist.add({ cidr: '203.0.113.0/24', label: 'office' });for await (const d of mgmt.databases.listAll()) console.log(d.name, d.status, d.endpoints.http);| Resource | Methods |
|---|---|
mgmt.organization(), mgmt.usage() | The token’s organization; this period’s usage |
mgmt.databases | list, listAll, create(name), get(name), delete(name) |
mgmt.backups | list(database), create(database), get(id) |
mgmt.restores | create({ backupId, databaseName }), pointInTime(database, { at, databaseName }) (a point_in_time clone), get(id) |
mgmt.clones | create(database, { name, source, at }) (latest_backup, fresh_snapshot, point_in_time), get(id) |
mgmt.exports | list(database), create(database), get(id), download(id, file) |
mgmt.ipAllowlist | list({ apiKeyId }), add({ cidr, label, apiKeyId }), remove(id) |
mgmt.apiKeys | list, listAll, create({ name, role, databases, expiresAt }), get, rotate(id, { overlapDays }), revoke(id) |
mgmt.managementTokens | list, listAll, create({ name, scope, expiresAt }) (the secret is in token, once), get(id), revoke(id); admin scope |
mgmt.members | list, listAll, remove(userId) |
mgmt.invitations | list, create({ email, role }), revoke(id) |
mgmt.support | list, listAll, create({ subject, body, category, severity, database }), get(number), reply(number, body) |
Options: token, url, timeoutMs (default 30,000), maxRetries
(default 2), fetch. Results use camelCase (readOnly, createdAt,
recoverySource, sourceCreatedAt, mintedBy).
list returns one page { data, nextCursor } (limit 1–100, cursor);
listAll walks every page. rate_limited, control_plane_unavailable,
502–504 and connection errors are retried with backoff. Every create sends an
Idempotency-Key (fresh, or the idempotencyKey you pass) and reuses it on
retries.
Browsers and edge runtimes
The client works wherever fetch exists, but a key in a browser is visible to
every visitor. Keep keys on a server or edge function; when a key must reach
users, use a read-only key scoped to one database. In browsers the client does
not set User-Agent.
Changelog
Release notes are in the package’s CHANGELOG.md on npm.