Skip to Content
Runtime

Runtime

@cyphra/runtime wraps the official Neo4j JavaScript driver with Cyphra’s compiled Cypher types (CompiledCypher from @cyphra/query).

Prefer import { CyphraClient, … } from "cyphra" if you use the cyphra meta-package (installation); subpackage imports are equivalent.

Client

import { cypher } from "@cyphra/query"; import { CyphraClient } from "@cyphra/runtime"; const client = new CyphraClient({ uri: process.env.NEO4J_URI!, user: process.env.NEO4J_USERNAME!, password: process.env.NEO4J_PASSWORD!, database: "neo4j", // optional, Neo4j 4+ log: ["warn", "error"], // optional: see Logging and tracing below }); await client.withSession(async (session) => { await client.runCompiled(session, cypher`RETURN 1 AS n`); }); await client.close();

Optional dialect is "neo4j" (default), "memgraph" or "falkordb": the Cypher flavour the OGM compiles to and the DDL the migrator writes (client.dialect). See Memgraph for what changes and what is not available there; detectDialect(client) reads it from the server.

To connect to FalkorDB, pass falkordb: { url, graph } instead of uri, user and password (it implies dialect: "falkordb" and needs the optional falkordb package). FalkorDB has no multi-statement transactions: see Transactions.

Optional driverConfig is passed through as the third argument to neo4j.driver (pool size, connectionAcquisitionTimeout, logging, etc.). Types: import Config from @cyphra/runtime or neo4j-driver.

Supported neo4j-driver versions

neo4j-driverStatusNode.js
6.xSupported20+
5.28.xSupported20+
< 5.28Not supported

@cyphra/runtime, @cyphra/migrator and @cyphra/better-auth declare neo4j-driver as a peer dependency (^5.28.3 || ^6.0.0), so your app and Cyphra share one copy of the driver. The cyphra meta-package and @cyphra/cli depend on it directly with the same range, so npm i cyphra works without installing the driver yourself, and a driver your project already has (5 or 6) is reused. npm 7+ and pnpm 8+ install peer dependencies automatically; with Yarn, add neo4j-driver next to @cyphra/runtime if you use the subpackages.

Cyphra only uses APIs that are the same in both majors (executeRead / executeWrite, run), and it recognises driver values by their markers (isInt, isDateTime, isDate, …), never with instanceof. The OGM builds its parameters with its own value classes (CypherInteger, CypherDateTime, …), which carry the same markers and fields as the driver’s, so the driver sends them as Cypher INTEGER, DATETIME and so on. Integers and temporals therefore round-trip the same way on 5 and 6, even if two copies of the driver end up installed, and over HTTP (below).

Using your own driver

Pass a Driver your application already created (from neo4j-driver 5.28+ or 6.x) instead of a URI and credentials. Cyphra then shares its connection pool and leaves its lifecycle to you: client.close() and the typed client’s $disconnect() do not close a driver you passed in.

import neo4j from "neo4j-driver"; import { CyphraClient } from "@cyphra/runtime"; import { createClient } from "./cyphra.gen.js"; const driver = neo4j.driver( process.env.NEO4J_URI!, neo4j.auth.basic(process.env.NEO4J_USERNAME!, process.env.NEO4J_PASSWORD!), ); const client = new CyphraClient({ driver, database: "neo4j" }); const db = createClient({ driver }); // typed client on the same driver // ... on shutdown await driver.close();

The driver option is typed structurally (DriverLike), so a Driver from another copy or major of neo4j-driver than the one Cyphra resolves is accepted too. The Session and ManagedTransaction types that Cyphra’s callbacks expose are those of the driver Cyphra resolves.

Sessions and transactions

  • session() — you own close(); prefer withSession(fn) so the session is always closed.
  • withReadTransaction / withWriteTransaction — delegate to the driver’s executeRead / executeWrite with a managed transaction.

Inside a transaction callback, use runCompiledTx, runCypherTx, queryRecordsTx, queryRecordTx, selectRecordsTx, or selectRecordTx — same behavior as the session variants, but routed through tx.run (required for writes and retry semantics).

import { cypher } from "@cyphra/query"; await client.withWriteTransaction(async (tx) => { await client.runCompiledTx(tx, cypher`CREATE (n:Tmp { id: ${id} })`); });

Executing queries

  • runCompiled(session, compiled) — run CompiledCypher from cypher\…`orSelectQuery.toCypher()`.
  • runCypher(session, strings, ...values) — tagged-template style on the client (same parameter rules as compileCypher).
  • queryRecords / queryRecord — runCompiled plus plain row objects (record.toObject()).
  • selectRecords / selectRecord — same for a SelectQuery.

Each of the above has a *Tx(tx, …) counterpart for use inside withWriteTransaction / withReadTransaction.

Lower-level helpers toPlainRecords and toPlainRecord map a driver Result (or compatible) to plain objects if you call session.run yourself.

Logging and tracing

Both new CyphraClient(...) and the typed createClient(...) take the same observability options. They are all off by default, and with none of them set statements run exactly as before.

import { trace } from "@opentelemetry/api"; import { createClient } from "./cyphra.gen.js"; const db = createClient({ uri: process.env.NEO4J_URI!, user: process.env.NEO4J_USERNAME!, password: process.env.NEO4J_PASSWORD!, log: ["query", "warn", "error"], // print to the console, or pass (event) => void tracer: trace.getTracer("my-app"), // optional OpenTelemetry spans }); const off = db.$on("query", (e) => { metrics.histogram("neo4j.query", e.durationMs, { model: e.model, op: e.operation }); }); off(); // remove the listener
  • log: an array of levels ("query", "warn", "error") printed with console.log / console.warn / console.error, or a function that receives every event.
  • db.$on(level, fn) (typed client) and client.on(level, fn) (CyphraClient): add a listener at any time; they return an unsubscribe function. Listeners run whatever log says, and a listener that throws never fails the query.
  • logParams (default false): include parameter values in events.
  • tracer: an OpenTelemetry Tracer (see OpenTelemetry).
  • traceQueryText (default false): add the Cypher text to statement spans.
  • warnMissingIndexes (default false): see Missing index warnings.
  • debug is deprecated: it is the same as log: ["query"], printed with console.debug.

A query event is emitted for each statement that completes:

type QueryEvent = { type: "query"; model?: string; // "Post" operation?: string; // "findMany", "$cypher", "graphql.read", ... text: string; // the Cypher sent to Neo4j params: Record<string, unknown>; // { p0: "<string>" } unless logParams: true durationMs: number; // until every record was received rows?: number; // records returned database?: string; transaction: boolean; // true inside $transaction / withWriteTransaction timestamp: Date; };

An error event has the same fields (without rows) plus message, code (the Neo4j status code, for example Neo.ClientError.Statement.SyntaxError), gqlStatus when the driver reports one, and error (the original error, which is still thrown to your code). Most OGM operations are one statement, nested writes and the read-back included; an upsert with nested writes, or a delete whose onDelete cascades loop back on a model, runs several, and emits a query event for each, all with the same model and operation. The driver may retry a transaction on transient errors, and each attempt emits its own events.

Parameter redaction

By default every parameter value is replaced by a type placeholder: "<string>", "<number>", "<boolean>", "<null>", "<list(3)>", "<Date>", "<Integer>", "<Float32Array(1536)>", and maps are described key by key ({ email: "<string>", age: "<number>" }). With logParams: true the values are included, except for keys that look like secrets (password, token, secret, apiKey, authorization, credential), which stay "<redacted>". Cyphra always sends values as parameters, so the query text itself holds no user data. Events never include the connection URI, user or password.

OpenTelemetry

Cyphra does not depend on OpenTelemetry. @opentelemetry/api is an optional peer dependency: pass any Tracer from it (1.x) as tracer, and register a tracer provider with a context manager as usual (the Node.js SDK does both):

import { NodeSDK } from "@opentelemetry/sdk-node"; import { trace } from "@opentelemetry/api"; new NodeSDK({ serviceName: "my-app" /* exporter, ... */ }).start(); const db = createClient({ uri, user, password, tracer: trace.getTracer("my-app") });

Each OGM operation is a span named cyphra.<Model>.<operation> (cyphra.Post.findMany, cyphra.$transaction, cyphra.$cypher), made active so that its statements and any span you start inside $transaction are its children. Each statement is a child span of kind CLIENT, named after its first clause and model (MATCH Post), with the database semantic conventions:

AttributeValue
db.system.nameneo4j
db.namespacethe database (database option, or the one the server reports)
db.operation.nameMATCH, CREATE, UNWIND, … (findMany etc. on operation spans)
db.query.textonly with traceQueryText: true; string literals are masked
db.response.returned_rowsrecords returned
server.addresshost, from the URI (or from the server for { driver })
server.portport
error.typethe Neo4j status code, or the error class

A failed statement records the exception and sets the span status to ERROR, on the statement span and on its operation span. Operation spans also carry cyphra.model.

@cyphra/graphql emits the same events and spans when you give it a client rather than a raw driver: the engine’s operations (findMany, createMany, …) for what compat.v7 runs on the shared engine, graphql.read / graphql.write for the statements of its compat compiler.

Missing index warnings

In development, warnMissingIndexes: true tells you which filters scan a whole label:

const db = createClient({ uri, user, password, warnMissingIndexes: process.env.NODE_ENV === "development", }); await db.post.findMany({ where: { title: "Hello" } }); // [cyphra:warn] Post.title is filtered without an index (label scan + filter): // add @index to Post.title in your schema.

For each distinct statement text that has a WHERE, Cyphra runs EXPLAIN once, in a separate session and without delaying the query. When the plan filters a property right on top of a NodeByLabelScan or AllNodesScan, and SHOW INDEXES lists no index on that label and property, it emits a warn event (kind: "missing-index", with label, property, model, operation and the statement text). Each property is reported once per client. When the field is already declared @id, @unique or @index, the warning says the database is missing it instead, so you know to apply your migrations. With no warn listener and no log, warnings are printed with console.warn.

It is off by default and you should keep it off in production: the cost is one EXPLAIN round trip per distinct statement (at most 1,000 per client) and one SHOW INDEXES every few seconds while new statements appear. A property that has an index is never reported, even when the planner chose a label scan for that statement (it can, on a small development database). client.close() and $disconnect() wait for pending checks.

HTTP transport (Edge, Workers)

Bolt needs TCP sockets, which Vercel Edge Functions and Cloudflare Workers do not offer. There, the client talks to the Neo4j Query API  over fetch instead: same createClient, same typed client, same results.

const db = createClient({ uri: "https://<id>.databases.neo4j.io", // Aura; http://localhost:7474 for a local server user: env.NEO4J_USERNAME, password: env.NEO4J_PASSWORD, });

An https:// or http:// URI selects the HTTP transport. To keep one NEO4J_URI for both Node.js (Bolt) and edge code, pass transport: "http" with the Bolt URI: neo4j+s://host maps to https://host and neo4j://host to http://host:7474.

OptionPurpose
user, passwordBasic auth
tokenBearer token (SSO) instead of user / password
databaseDatabase name (default neo4j)
fetchCustom fetch: tests, a proxy, a Worker service binding
headersExtra headers on every request
maxRetryTimeMsHow long transactions retry transient errors (default 30 000)
maxConcurrencyTransactions and statements in flight at once (default 4)
acquisitionTimeoutMsHow long a statement waits for a free slot (default 60 000)

Requirements. Neo4j 5.19 or later, or Aura. The Query API is on by default from Neo4j 5.26; on 5.19 to 5.25, add QUERY_API_ENDPOINTS to server.http_enabled_modules. A self-managed server must expose its HTTP connector (port 7474, or 7473 with TLS), behind HTTPS in production.

Edge build. @cyphra/runtime and cyphra ship a second build without neo4j-driver and without Node.js built-ins. Bundlers pick it automatically under the workerd (Cloudflare), edge-light (Vercel Edge) and worker export conditions, so the generated client needs no change. Import @cyphra/runtime/edge to choose it yourself. In that build, a Bolt URI throws an error that points to the HTTP transport, and the cyphra package leaves out @cyphra/migrator.

Vercel Edge route

app/api/users/route.ts
import { createClient } from "@/lib/cyphra.gen"; export const runtime = "edge"; const db = createClient({ uri: process.env.NEO4J_URI!, // neo4j+s://<id>.databases.neo4j.io transport: "http", user: process.env.NEO4J_USERNAME!, password: process.env.NEO4J_PASSWORD!, }); export async function GET() { const users = await db.user.findMany({ take: 20, orderBy: { createdAt: "desc" } }); return Response.json(users); }

Cloudflare Worker

src/index.ts
import { createClient } from "./cyphra.gen"; type Env = { NEO4J_URL: string; NEO4J_USERNAME: string; NEO4J_PASSWORD: string }; let db: ReturnType<typeof createClient> | undefined; export default { async fetch(request: Request, env: Env): Promise<Response> { db ??= createClient({ uri: env.NEO4J_URL, // https://<id>.databases.neo4j.io user: env.NEO4J_USERNAME, password: env.NEO4J_PASSWORD, }); const email = new URL(request.url).searchParams.get("email") ?? ""; const user = await db.user.findUnique({ where: { email }, include: { posts: true } }); return user ? Response.json(user) : new Response("Not found", { status: 404 }); }, };

Set the password with wrangler secret put NEO4J_PASSWORD. No nodejs_compat flag is needed.

What runs over HTTP

Everything the typed client does: CRUD, nested writes, upsert, aggregate / groupBy, traversals and shortest paths, vector and full-text search, $cypher and $transaction. CI runs the whole OGM integration suite over both transports. Logging, OpenTelemetry spans and missing-index warnings work the same (server.address is the HTTP host).

  • An operation that is one statement and writes nothing when it fails (reads, create and update with their nested creates, upsert, delete, the *Many writes, $cypher) is one auto-commit POST /db/{database}/query/v2, sent with accessMode: "READ" for reads.
  • Other operations (a nested connect, checked after the statement ran; an upsert with nested writes) and $transaction use an explicit transaction: the first statement opens it (POST …/tx), the others follow (POST …/tx/{id}), then …/commit, or DELETE on error. The neo4j-cluster-affinity header Aura returns is sent back on every request of the transaction.
  • Transient errors (deadlocks, an unreachable server) retry the statement or the whole transaction callback, like the driver’s managed transactions.
  • Values use the Query API’s typed JSON: a schema Int is sent as an Integer, a JS number as a Float (as with Bolt). Results decode into the same JS values as with Bolt.
  • Errors are Neo4jHttpErrors with the Neo4j code (Neo.ClientError.Schema.ConstraintValidationFailed, …) and the HTTP status. The OGM client turns uniqueness violations into a UniqueConstraintError, as with Bolt.

Limitations

  • Latency. Each request is a round trip: one for most operations, two (the statement, then the commit) for one that needs an explicit transaction, and one more per statement inside $transaction. Keep the database in the same region as your functions.
  • No streaming. The server sends the whole result in one response: bound large reads with take.
  • Transactions. Neo4j supports explicit Query API transactions on Aura and single-instance servers, not on self-managed clusters. A transaction idle for 60 seconds is rolled back (server.queryapi.transaction_idle_timeout).
  • Concurrency. Neo4j answers Query API requests from a fixed pool of HTTP worker threads (one per CPU core by default, server.threads.worker_count), and a request waiting for a lock keeps its thread. If every thread waits on a lock held by an open transaction, the request that would commit it gets no thread and they all hang. Each client therefore keeps at most maxConcurrency transactions and statements in flight (default 4) and queues the rest. Many isolates hitting one small self-managed server can still exhaust it: raise server.threads.worker_count there.
  • Low-level API. client.session() and rawDriver return small HTTP stand-ins with run, executeRead, executeWrite and close, whose records have get, keys and toObject. There is no Result streaming, executeQuery or reactive API, and { driver } is Bolt only.
  • CLI and migrations. cyphra CLI commands and @cyphra/migrator run on Node.js and are meant for Bolt URIs. Run cyphra migrate deploy from your build or CI, not from the edge.

See also

  • Queries — cypher tag and SelectQuery builder
  • Migrations — create the indexes the warnings ask for
  • Example app — optional live round-trip with NEO4J_* env vars
Last updated on