CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-neo4j-driver

The official Neo4j driver for JavaScript applications, enabling connection to and interaction with Neo4j graph databases.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Neo4j Driver

The Neo4j JavaScript driver provides the official client for connecting to and interacting with Neo4j graph databases. It offers a comprehensive API for executing Cypher queries, managing database sessions and transactions, with support for both callback and reactive programming patterns through RxJS integration.

Package Information

  • Package Name: neo4j-driver
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install neo4j-driver

Core Imports

import neo4j from "neo4j-driver";

Named imports:

import { driver, auth, types, session } from "neo4j-driver";

For CommonJS:

const neo4j = require("neo4j-driver");
// or
const { driver, auth, types, session } = require("neo4j-driver");

Basic Usage

import { driver, auth } from "neo4j-driver";

// Create driver instance
const neo4jDriver = driver(
  "neo4j://localhost:7687",
  auth.basic("username", "password")
);

// Create session and run query
const session = neo4jDriver.session();
try {
  const result = await session.run(
    "CREATE (p:Person {name: $name}) RETURN p",
    { name: "Alice" }
  );
  
  result.records.forEach(record => {
    const person = record.get("p");
    console.log(person.properties.name);
  });
} finally {
  await session.close();
}

// Close driver
await neo4jDriver.close();

Architecture

Neo4j Driver is built around several key components:

  • Driver: Main entry point managing connection pools and providing sessions
  • Session Management: Standard and reactive sessions for query execution
  • Transaction Management: Explicit transactions and auto-managed transactions with retry logic
  • Result Handling: Streaming and eager result processing with comprehensive metadata
  • Data Types: Native JavaScript representations of Neo4j graph and temporal types
  • Authentication: Multiple auth methods including basic, Kerberos, and custom tokens
  • Connection Management: Automatic routing, load balancing, and connection pooling

Capabilities

Driver Management

Core driver creation and connection management functionality for establishing and maintaining database connections.

function driver(
  url: string,
  authToken?: AuthToken | AuthTokenManager,
  config?: Config
): Driver;

function hasReachableServer(
  url: string,
  config?: Pick<Config, 'logging'>
): Promise<true>;

Driver Management

Session Operations

Session management for executing queries and managing database interactions with support for read/write modes and transaction handling.

interface Driver {
  session(config?: SessionConfig): Session;
  rxSession(config?: SessionConfig): RxSession;
  close(): Promise<void>;
}

interface Session {
  run(query: string, parameters?: Parameters): Promise<Result>;
  beginTransaction(config?: TransactionConfig): Promise<Transaction>;
  executeRead<T>(work: (tx: ManagedTransaction) => Promise<T>): Promise<T>;
  executeWrite<T>(work: (tx: ManagedTransaction) => Promise<T>): Promise<T>;
  close(): Promise<void>;
}

Session Operations

Transaction Management

Transaction handling including explicit transactions and managed transactions with automatic retry logic for robust database operations.

interface Transaction {
  run(query: string, parameters?: Parameters): Promise<Result>;
  commit(): Promise<void>;
  rollback(): Promise<void>;
  isOpen(): boolean;
}

interface ManagedTransaction {
  run(query: string, parameters?: Parameters): Promise<Result>;
}

Transaction Management

Reactive Programming

RxJS-based reactive API for streaming query results and handling large datasets with backpressure support.

interface RxSession {
  run(query: string, parameters?: Parameters): RxResult;
  beginTransaction(config?: TransactionConfig): Observable<RxTransaction>;
  executeRead<T>(work: (tx: RxManagedTransaction) => Observable<T>): Observable<T>;
  executeWrite<T>(work: (tx: RxManagedTransaction) => Observable<T>): Observable<T>;
  close(): Observable<void>;
}

interface RxResult {
  keys(): Observable<string[]>;
  records(): Observable<Record>;
  consume(): Observable<ResultSummary>;
}

Reactive Programming

Graph Data Types

Neo4j graph data types including nodes, relationships, and paths with comprehensive type checking utilities.

interface Node {
  identity: Integer;
  labels: string[];
  properties: Record<string, any>;
}

interface Relationship {
  identity: Integer;
  start: Integer;
  end: Integer;
  type: string;
  properties: Record<string, any>;
}

interface Path {
  start: Node;
  end: Node;
  length: number;
  segments: PathSegment[];
  nodes: Node[];
  relationships: Relationship[];
}

Graph Data Types

Temporal Data Types

Neo4j temporal data types including dates, times, and durations with timezone support and comprehensive type checking.

interface Date {
  year: Integer;
  month: Integer;
  day: Integer;
  toString(): string;
}

interface DateTime {
  year: Integer;
  month: Integer;
  day: Integer;
  hour: Integer;
  minute: Integer;
  second: Integer;
  nanosecond: Integer;
  timeZoneOffsetSeconds?: Integer;
  timeZoneId?: string;
}

interface Duration {
  months: Integer;
  days: Integer;
  seconds: Integer;
  nanoseconds: Integer;
}

Temporal Data Types

Authentication

Comprehensive authentication system supporting basic, Kerberos, bearer token, and custom authentication methods.

interface AuthToken {
  scheme: string;
  principal: string;
  credentials: string;
  realm?: string;
  parameters?: Record<string, any>;
}

declare const auth: {
  basic(username: string, password: string, realm?: string): AuthToken;
  kerberos(base64EncodedTicket: string): AuthToken;
  bearer(base64EncodedToken: string): AuthToken;
  custom(
    principal: string,
    credentials: string,
    realm: string,
    scheme: string,
    parameters?: Parameters
  ): AuthToken;
};

Authentication

Error Handling

Comprehensive error handling with retryable error detection and detailed error information for robust application development.

class Neo4jError extends Error {
  code: string;
  constructor(message: string, code?: string);
}

function isRetryableError(error: any): boolean;

declare const error: {
  SERVICE_UNAVAILABLE: string;
  SESSION_EXPIRED: string;
  PROTOCOL_ERROR: string;
};

Error Handling

Types

Core Configuration Types

interface Config {
  encrypted?: EncryptionLevel;
  trust?: TrustStrategy;
  trustedCertificates?: string[];
  knownHosts?: string;
  maxConnectionLifetime?: number;
  maxConnectionPoolSize?: number;
  connectionAcquisitionTimeout?: number;
  disableLosslessIntegers?: boolean;
  logging?: LoggingConfig;
  resolver?: (address: string) => string[] | Promise<string[]>;
  userAgent?: string;
  boltAgent?: Record<string, any>;
  notificationFilter?: NotificationFilter;
  telemetryDisabled?: boolean;
  clientCertificate?: ClientCertificate | ClientCertificateProvider;
}

interface SessionConfig {
  defaultAccessMode?: SessionMode;
  bookmarks?: string | string[] | Bookmarks;
  database?: string;
  impersonatedUser?: string;
  bookmarkManager?: BookmarkManager;
  notificationFilter?: NotificationFilter;
  auth?: AuthToken | AuthTokenManager;
}

interface TransactionConfig {
  timeout?: number;
  metadata?: Record<string, any>;
}

type EncryptionLevel = "ENCRYPTION_ON" | "ENCRYPTION_OFF";
type TrustStrategy = "TRUST_ALL_CERTIFICATES" | "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES";
type SessionMode = "READ" | "WRITE";

Additional Utilities

/** Bookmark manager factory and utilities */
declare const bookmarkManager: {
  memory(): BookmarkManager;
};

/** Result transformation utilities */
declare const resultTransformers: {
  eagerTransformer(): ResultTransformer;
};

/** Routing control constants */
declare const routing: {
  READ: RoutingControl;
  WRITE: RoutingControl;
};

/** Client certificate provider utilities */
declare const clientCertificateProviders: ClientCertificateProviders;

/** Notification category constants */
declare const notificationCategory: NotificationCategory;

/** Notification classification constants */
declare const notificationClassification: NotificationClassification;

/** Notification severity level constants */
declare const notificationSeverityLevel: NotificationSeverityLevel;

/** Notification filter utilities for disabled categories */
declare const notificationFilterDisabledCategory: NotificationFilterDisabledCategory;

/** Notification filter utilities for disabled classifications */
declare const notificationFilterDisabledClassification: NotificationFilterDisabledClassification;

/** Notification filter utilities for minimum severity levels */
declare const notificationFilterMinimumSeverityLevel: NotificationFilterMinimumSeverityLevel;

/** Type constructors collection */
declare const types: {
  Node: typeof Node;
  Relationship: typeof Relationship;
  UnboundRelationship: typeof UnboundRelationship;
  PathSegment: typeof PathSegment;
  Path: typeof Path;
  Result: typeof Result;
  EagerResult: typeof EagerResult;
  ResultSummary: typeof ResultSummary;
  Record: typeof Record;
  Point: typeof Point;
  Date: typeof Date;
  DateTime: typeof DateTime;
  Duration: typeof Duration;
  LocalDateTime: typeof LocalDateTime;
  LocalTime: typeof LocalTime;
  Time: typeof Time;
  Integer: typeof Integer;
};

Integer Utilities

/** Create Integer from number or string */
function int(value: number | string): Integer;

/** Check if value is an Integer instance */
function isInt(value: any): value is Integer;

/** Integer utility functions */
declare const integer: {
  toNumber(value: Integer): number;
  toString(value: Integer): string;
  inSafeRange(value: Integer): boolean;
};

/** Spatial utility functions */
declare const spatial: {
  isPoint(value: any): value is Point;
};

/** Temporal utility functions */
declare const temporal: {
  isDate(value: any): value is Date;
  isDateTime(value: any): value is DateTime;
  isLocalDateTime(value: any): value is LocalDateTime;
  isTime(value: any): value is Time;
  isLocalTime(value: any): value is LocalTime;
  isDuration(value: any): value is Duration;
};

/** Graph utility functions */
declare const graph: {
  isNode(value: any): value is Node;
  isRelationship(value: any): value is Relationship;
  isUnboundRelationship(value: any): value is UnboundRelationship;
  isPath(value: any): value is Path;
  isPathSegment(value: any): value is PathSegment;
};

/** Logging configuration utilities */
declare const logging: {
  console: (level?: "DEBUG" | "INFO" | "WARN" | "ERROR") => LoggingConfig;
};

/** Authentication token manager utilities */
declare const authTokenManagers: {
  staticAuthTokenManager: (options: { authToken: AuthToken }) => AuthTokenManager;
};

/** Session access mode constants */
declare const session: {
  READ: SessionMode;
  WRITE: SessionMode;
};

Utility Types

type Parameters = Record<string, any>;

interface LoggingConfig {
  level: "DEBUG" | "INFO" | "WARN" | "ERROR";
  logger: (level: string, message: string) => void;
}

interface Integer {
  low: number;
  high: number;
  toString(): string;
  toNumber(): number;
  equals(other: Integer): boolean;
  compare(other: Integer): number;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/neo4j-driver@5.28.x
Publish Source
CLI
Badge
tessl/npm-neo4j-driver badge