MCPInstall

neo4j-driver-javascript-skill

Neo4j JavaScript/TypeScript Driver v6 — driver lifecycle, executeQuery, managed transactions (executeRead/executeWrite), session.run, Integer handling, JSON serialization, record access, async/await patterns, TypeScript types, error handling, and connection setup for Node.js and browser. Use when writing JS/TS code that connects to Neo4j — neo4j.driver(), executeQuery, executeRead, executeWrite, session.run, neo4j.int, record.get, Integer, BookmarkManager, bolt://, neo4j+s://. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver version migration — use neo4j-migration-skill.

Installs
404
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/neo4j-contrib/neo4j-skills --skill neo4j-driver-javascript-skill
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads neo4j-driver-javascript-skill automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

When to Use

  • Writing JS/TS code that connects to Neo4j (Node.js or browser)
  • Setting up driver, sessions, transactions, or query execution
  • Debugging Integer handling, result consumption, session leaks, async errors
  • TypeScript type annotations for driver objects

When NOT to Use

  • Writing/optimizing Cypher → neo4j-cypher-skill
  • Upgrading driver version → neo4j-migration-skill
  • RxJS session API → references/rxjs-session.md

Install

npm install neo4j-driver   # or: yarn add neo4j-driver

Environment Variables

Load connection config from environment — never hardcode credentials.

# .env file (add to .gitignore)
NEO4J_URI=neo4j+s://xxx.databases.neo4j.io
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=secret
NEO4J_DATABASE=neo4j
// npm install dotenv (for Node.js < 20 or when .env auto-load is off)
import 'dotenv/config'   // or: require('dotenv').config()

const URI      = process.env.NEO4J_URI
const USER     = process.env.NEO4J_USERNAME
const PASSWORD = process.env.NEO4J_PASSWORD
const DATABASE = process.env.NEO4J_DATABASE ?? 'neo4j'

Node 20+ natively loads .env with --env-file .env. Next.js / Vite auto-load .env — no dotenv import needed.


Driver Lifecycle

Create one driver instance at startup. Share everywhere. Never create per-request.

// CommonJS
const neo4j = require('neo4j-driver')
// ESM / TypeScript
import neo4j from 'neo4j-driver'

const driver = neo4j.driver(
  process.env.NEO4J_URI,                              // 'neo4j+s://xxx.databases.neo4j.io'
  neo4j.auth.basic(process.env.NEO4J_USER, process.env.NEO4J_PASSWORD)
)
await driver.verifyConnectivity()   // fail fast on startup if unreachable
// On shutdown:
await driver.close()

URI schemes:

SchemeTransportUse
neo4j+s://TLS + cluster routingAura; production clusters
neo4j://plaintext + cluster routinglocal dev cluster
bolt+s://TLS, single instancesingle Neo4j instance with TLS
bolt://plaintext, single instancelocal single instance

Auth options:

neo4j.auth.basic(user, password)   // username/password
neo4j.auth.bearer(token)           // SSO / JWT
neo4j.auth.kerberos(base64Ticket)  // Kerberos
neo4j.auth.none()                  // unauthenticated (dev only)

Singleton for web frameworks — create once, import everywhere:

// db.js
let _driver = null
export function getDriver() {
  if (!_driver) _driver = neo4j.driver(process.env.NEO4J_URI,
    neo4j.auth.basic(process.env.NEO4J_USER, process.env.NEO4J_PASSWORD))
  return _driver
}
export async function closeDriver() {
  if (_driver) { await _driver.close(); _driver = null }
}

Serverless (Lambda/Vercel/Workers): keep maxConnectionPoolSize: 5; no guaranteed SIGTERM.


Choose the Right API

APIUse whenAuto-retryResult
driver.executeQuery()Default for most queries✅eager (all records)
session.executeRead/Write()Large results, streaming, multi-query tx✅lazy stream
session.run()LOAD CSV, CALL IN TRANSACTIONS, scripts❌lazy stream

executeQuery — Default

const { records, summary, keys } = await driver.executeQuery(
  'MATCH (p:Person {name: $name})-[:KNOWS]->(f) RETURN f.name AS name',
  { name: 'Alice' },
  { database: 'neo4j', routing: neo4j.routing.READ }
)
for (const record of records) {
  console.log(record.get('name'))   // use .get() — records are NOT plain objects
}

// Write and count results
const { summary: s } = await driver.executeQuery(
  'CREATE (p:Person {name: $name, age: $age})',
  { name: 'Bob', age: neo4j.int(30) },
  { database: 'neo4j' }
)
console.log(s.counters.updates().nodesCreated)   // ✅ must call .updates()

Always specify database — omitting causes an extra round-trip.

❌ Never template-literal Cypher:

// ❌ injection risk + disables plan caching
await driver.executeQuery(`MATCH (p:Person {name: '${name}'}) RETURN p`)
// ✅ parameterised
await driver.executeQuery('MATCH (p:Person {name: $name}) RETURN p', { name })

Managed Transactions (executeRead / executeWrite)

Auto-retried on transient failures. Consume records inside the callback — the stream is gone when the callback returns.

const session = driver.session({ database: 'neo4j' })
try {
  const names = await session.executeRead(async tx => {
    const result = await tx.run(
      'MATCH (p:Person) WHERE p.name STARTS WITH $prefix RETURN p.name AS name',
      { prefix: 'Al' }
    )
    // ✅ collect() while tx is open; return plain data
    return (await result.collect()).map(r => r.get('name'))
  })

  await session.executeWrite(async tx => {
    await tx.run('MERGE (p:Person {name: $name})', { name: 'Carol' })
  })
} finally {
  await session.close()   // always in finally
}

Critical: await tx.run() returns a stream handle, not records.

// ❌ returns stream; tx closes; records = []
return await tx.run('MATCH (p:Person) RETURN p.name AS name')

// ✅ collect fully inside callback
const result = await tx.run('MATCH (p:Person) RETURN p.name AS name')
return (await result.collect()).map(r => r.get('name'))

// ✅ or stream with for-await
for await (const record of result) { names.push(record.get('name')) }

Callback may execute more than once (retry on transient failure) — no side effects inside:

// ❌ fetch() called on every retry
await session.executeWrite(async tx => {
  await fetch('https://api.example.com/notify')
  await tx.run('CREATE ...')
})
// ✅ side effects after confirmed commit
await session.executeWrite(async tx => { await tx.run('MERGE ...') })
await fetch('https://api.example.com/notify')

session.run — Implicit Transactions

Not auto-retried. Use for LOAD CSV / CALL IN TRANSACTIONS / scripting only.

const session = driver.session({ database: 'neo4j' })
try {
  const result = await session.run('CREATE (p:Person {name: $name}) RETURN p', { name: 'Alice' })
  console.log(result.summary.counters.updates().nodesCreated)
} finally {
  await session.close()
}

Session Close — Always in finally

// ❌ session leaks if executeRead rejects
session.executeRead(async tx => { ... })
  .then(result => doSomething(result))
  .then(() => session.close())

// ✅ guaranteed close
try {
  const result = await session.executeRead(async tx => { ... })
  doSomething(result)
} finally {
  await session.close()
}

// ✅ promise-chain equivalent
session.executeRead(async tx => { ... })
  .then(doSomething)
  .catch(handleError)
  .finally(() => session.close())

Integer Handling

Neo4j integers are 64-bit; JS Number is IEEE 754 (safe up to 2^53−1). Driver returns custom Integer by default.

Three modes:

// Mode 1 (default): Integer class — safe for all values, requires conversion
const driver1 = neo4j.driver(URI, auth)
// record.get('count') → Integer { low: 42, high: 0 }

// Mode 2: native JS number — only safe within Number.MAX_SAFE_INTEGER
const driver2 = neo4j.driver(URI, auth, { disableLosslessIntegers: true })
// record.get('count') → 42

// Mode 3: BigInt — precise but breaks JSON.stringify
const driver3 = neo4j.driver(URI, auth, { useBigInt: true })
// record.get('count') → 42n

Working with Integer class:

const count = record.get('count')        // Integer { low: 42, high: 0 }
neo4j.isInt(count)                       // true
neo4j.integer.inSafeRange(count)         // check before toNumber()
count.toNumber()                         // 42  (only safe within MAX_SAFE_INTEGER)
count.toString()                         // '42' (always safe)
count.toBigInt()                         // 42n

// Send integer parameter — plain JS number sends as FLOAT
await driver.executeQuery('CREATE (p:Person {age: $age})', { age: neo4j.int(30) })

JSON serialization pitfalls:

// ❌ Integer → {"low":42,"high":0}
JSON.stringify({ age: record.get('age') })
// ❌ BigInt → TypeError: Do not know how to serialize a BigInt
// ✅ convert first
JSON.stringify({ age: record.get('age').toNumber() })
// ✅ or use disableLosslessIntegers: true
// ❌ temporal types → {} silently
JSON.stringify({ dt: record.get('created') })
// ✅
JSON.stringify({ dt: record.get('created').toString() })

Record Access

Records are not plain objects — use .get():

const record = records[0]
record.get('name')    // ✅ by key
record.get(0)         // ✅ by index
record.keys           // ['name', 'age']
record.has('name')    // true
record.name           // ❌ undefined
record['name']        // ❌ undefined

record.toObject() returns plain JS keys but values are still driver types (Integers, temporals). Not JSON-safe without conversion.


Error Handling

import { Neo4jError, SERVICE_UNAVAILABLE, SESSION_EXPIRED } from 'neo4j-driver'

try {
  await driver.executeQuery('...', {}, { database: 'neo4j' })
} catch (err) {
  if (err instanceof Neo4jError) {
    if (err.code === 'Neo.ClientError.Schema.ConstraintValidationFailed') { /* unique constraint */ }
    if (err.code === SERVICE_UNAVAILABLE) { /* unreachable */ }
    if (err.code === SESSION_EXPIRED)     { /* open a new session */ }
    if (err.retriable) { /* transient — executeQuery already retried to exhaustion */ }
  }
}

executeQuery and executeRead/Write auto-retry retriable errors. session.run does not.


TypeScript

import neo4j, { Driver, Session, ManagedTransaction, Record, Node, Integer } from 'neo4j-driver'

const driver: Driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD))
const session: Session = driver.session({ database: 'neo4j' })

const names: string[] = await session.executeRead(
  async (tx: ManagedTransaction): Promise<string[]> => {
    const result = await tx.run('MATCH (p:Person) RETURN p.name AS name')
    return (await result.collect()).map((r: Record) => r.get('name') as string)
  }
)

// Typed node — Integer generic changes with disableLosslessIntegers
const node = record.get('p') as Node<Integer>
const age: number = node.properties.age.toNumber()
// With disableLosslessIntegers: true → Node<number>; age is already number

Batch Writes with UNWIND

// ❌ one transaction per item
for (const p of people) { await driver.executeQuery('CREATE ...', p) }

// ✅ single transaction
await driver.executeQuery(
  `UNWIND $people AS person
   MERGE (p:Person {name: person.name})
   SET p.age = person.age`,
  { people },   // array of plain objects; numeric fields must be JS numbers, not neo4j.int()
  { database: 'neo4j' }
)

Common Mistakes

MistakeFix
Template literal CypherUse $param placeholders
record.name / record['name']record.get('name')
JSON.stringify on Integer.toNumber() or disableLosslessIntegers
JSON.stringify on temporal.toString() first
summary.counters.nodesCreatedsummary.counters.updates().nodesCreated
Omit databaseAlways { database: 'neo4j' }
Return result from tx callbackReturn await result.collect() or mapped data
.then(() => session.close())try/finally { await session.close() }
Side effects inside tx callbackMove outside — callback may retry
New driver per requestCreate once at startup
bolt:// or neo4j:// in browserUse neo4j+s:// (WSS)
Integer in UNWIND arrayConvert to plain JS Number first
maxConnectionPoolSize: 100 in serverlessUse 5–10 per function instance

References

Load on demand:

  • references/data-types.md — full type mapping table, temporal types, graph types (Node/Relationship/Path), spatial types (Point/WGS-84/Cartesian), neo4j.UUID [6.2+], toNative() conversion helper
  • references/advanced-patterns.md — explicit transactions, causal consistency/bookmarks, connection pool tuning, result transformers, lazy streaming, repository pattern
  • references/browser-usage.md — WebSocket URIs, CORS, bundler config, security guidance
  • references/rxjs-session.md — RxJS session API (rxSession.run(), observable patterns)

Checklist

  • One driver instance created at startup; shared everywhere
  • database specified on every query/session
  • await driver.verifyConnectivity() called at startup
  • session.close() in finally block
  • Records accessed with .get() — not dot/bracket notation
  • Integer .toNumber() / .toString() called before JSON serialization
  • Temporal .toString() called before JSON serialization
  • summary.counters.updates() called before accessing counter fields
  • $param placeholders used — no string concatenation in Cypher
  • Tx callback returns plain data (not stream); side effects outside callback
  • Write uses neo4j.int() for integer parameters
  • executeRead for reads; executeWrite for writes
  • Browser: neo4j+s:// URI (WebSocket)

FAQ

What does the neo4j-driver-javascript-skill skill do?

Neo4j JavaScript/TypeScript Driver v6 — driver lifecycle, executeQuery, managed transactions (executeRead/executeWrite), session.run, Integer handling, JSON serialization, record access, async/await patterns, TypeScript types, error handling, and connection setup for Node.js and browser. Use when writing JS/TS code that connects to Neo4j — neo4j.driver(), executeQuery, executeRead, executeWrite, session.run, neo4j.int, record.get, Integer, BookmarkManager, bolt://, neo4j+s://. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver version migration — use neo4j-migration-skill.

How do I install neo4j-driver-javascript-skill?

Run npx skills add https://github.com/neo4j-contrib/neo4j-skills --skill neo4j-driver-javascript-skill in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/neo4j-driver-javascript-skill/ (personal) or .claude/skills/neo4j-driver-javascript-skill/ (project).

Which AI agents can use neo4j-driver-javascript-skill?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is neo4j-driver-javascript-skill safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains neo4j-driver-javascript-skill?

It is published by neo4j-contrib in neo4j-contrib/neo4j-skills. It has 404 recorded installs.

More from neo4j-contrib/neo4j-skills

View all →

neo4j-cypher-skill

neo4j-contrib/neo4j-skills

Generates, optimizes, and validates Cypher 25 queries for Neo4j 2025.x and 2026.x. Use when writing new Cypher queries, optimizing slow queries, graph pattern matching, vector or fulltext search, subqueries, or batch writes. Covers MATCH, MERGE, CREATE, WITH, RETURN, CALL, UNWIND, FOREACH, LOAD CSV, SEARCH, expressions, functions, indexes, and subqueries. Does NOT handle driver migration or API changes — use neo4j-migration-skill. Does NOT cover DB administration or server ops — use neo4j-cli-tools-skill.

Backend & APIs1.5K installs

neo4j-modeling-skill

neo4j-contrib/neo4j-skills

Design, review, and refactor Neo4j graph data models. Use when choosing node labels vs relationship types vs properties, migrating relational/document schemas to graph, detecting anti-patterns (generic labels, supernodes, missing constraints), designing intermediate nodes for n-ary relationships, enforcing schema with constraints and indexes, or assessing an existing model against graph modeling best practices. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT handle Spring Data Neo4j entity mapping — use neo4j-spring-data-skill. Does NOT handle GraphQL type definitions — use neo4j-graphql-skill. Does NOT handle data import — use neo4j-import-skill.

Backend & APIs1.2K installs

neo4j-graphrag-skill

neo4j-contrib/neo4j-skills

Build GraphRAG retrieval pipelines on Neo4j using the neo4j-graphrag Python package (v1.22.0+). Covers retriever selection (VectorRetriever, HybridRetriever, VectorCypherRetriever, HybridCypherRetriever, Text2CypherRetriever, ToolsRetriever), external vector DB retrievers (Weaviate, Pinecone, Qdrant), retrievalquery Cypher fragments, queryparams, filters, GraphRAG pipeline wiring (GraphRAG + LLM + prompt), all LLM providers (OpenAI, Anthropic, Gemini/VertexAI, Bedrock, Cohere, Mistral, Ollama), embedder setup, index creation, token usage tracking, Cypher 25 SEARCH clause, and LangChain/LlamaIndex integration. Does NOT handle KG construction — use neo4j-document-import-skill. Does NOT handle plain vector search — use neo4j-vector-index-skill. Does NOT handle GDS analytics — use neo4j-gds-skill. Does NOT handle agent memory — use neo4j-agent-memory-skill.

AI & Agents1.1K installs

neo4j-driver-python-skill

neo4j-contrib/neo4j-skills

Neo4j Python Driver v6 — driver lifecycle, executequery, managed and explicit transactions, async (AsyncGraphDatabase), result handling, data type mapping, error handling, UNWIND batching, connection pool tuning, and causal consistency. Use when writing Python code that connects to Neo4j via GraphDatabase.driver, executequery, executeread, executewrite, AsyncGraphDatabase, neo4j.Result, or RoutingControl. Package name is neo4j (not neo4j-driver) since v6. Python =3.10 required. Does NOT handle Cypher query authoring — use neo4j-cypher-skill. Does NOT cover driver upgrades or breaking changes — use neo4j-migration-skill. Does NOT cover GraphRAG pipelines (neo4j-graphrag package) — use neo4j-graphrag-skill.

neo4j-document-import-skill

neo4j-contrib/neo4j-skills

Ingests unstructured and semi-structured documents into Neo4j as a knowledge graph. Use when chunking PDFs, HTML, plain text, or Markdown; extracting entities and relationships from text with an LLM (SimpleKGPipeline, neo4j-graphrag); loading JSON via apoc.load.json; building Document→Chunk→Entity graph structures; or connecting LangChain/LlamaIndex document loaders to Neo4j. Covers neo4j-graphrag SimpleKGPipeline, LLM Graph Builder web UI, entity resolution, chunking strategies, and graph schema design for RAG pipelines. Does NOT handle structured CSV/relational import — use neo4j-import-skill. Does NOT handle GraphRAG retrieval after ingestion — use neo4j-graphrag-skill. Does NOT handle vector index creation — use neo4j-vector-search-skill.

AI & Agents934 installs

neo4j-query-tuning-skill

neo4j-contrib/neo4j-skills

Diagnoses and fixes slow Neo4j Cypher queries by reading execution plans, identifying bad operators (AllNodesScan, CartesianProduct, Eager, NodeByLabelScan), and prescribing fixes (indexes, hints, query rewrites, runtime selection). Use when a query is slow, when EXPLAIN or PROFILE output needs interpretation, when dbHits or pageCacheHitRatio are poor, when cardinality estimation diverges from actuals, or when deciding between slotted/pipelined/parallel runtimes. Covers USING INDEX / USING SCAN / USING JOIN hints, db.stats.retrieve, SHOW QUERIES, SHOW TRANSACTIONS, TERMINATE TRANSACTION. Does NOT write new Cypher from scratch — use neo4j-cypher-skill. Does NOT cover GDS algorithm tuning — use neo4j-gds-skill. Does NOT cover index/constraint creation syntax details — use neo4j-cypher-skill references/indexes.md.

916 installs

Popular code quality & workflow skills

View category →

grill-me

mattpocock/skills

A relentless interview to sharpen a plan or design.

Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.

handoff

mattpocock/skills

Compact the current conversation into a handoff document for another agent to pick up.

domain-modeling

mattpocock/skills

Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.

codebase-design

mattpocock/skills

Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.

diagnosing-bugs

mattpocock/skills

Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.