Neo4j with NestJS
@cyphra/nestjs connects a NestJS app to Neo4j: CyphraModule.forRootAsync builds the generated
Cyphra client from ConfigService, @InjectCyphra() injects it with its full types,
@Transactional() runs a service method (and every service it calls) in one transaction, and
CyphraHealthIndicator reports the database in a @nestjs/terminus health check. The driver is
closed when the application shuts down.
Tested with NestJS 12.4, @nestjs/config 12.1, @nestjs/terminus 12.1, Node.js 22 and Neo4j 5
(the example app and its
end-to-end tests). The module and @Transactional() are also tested on NestJS 10 and 11.
Cyphra is ESM-only. nest new in NestJS 12 creates an ES module project ("type": "module",
"module": "nodenext"), which works as is. In a CommonJS Nest 10 or 11 project,
require("cyphra") fails with ERR_PACKAGE_PATH_NOT_EXPORTED: switch the project to ESM first.
Steps
Install
npm i cyphra @cyphra/nestjs @nestjs/config
npm i -D @cyphra/cli
npm i @nestjs/terminus # optional: for the health check@nestjs/common, @nestjs/core (10, 11 or 12) and reflect-metadata are peer dependencies that a
Nest project already has.
Describe your graph and generate the client
node Account {
id String @id @default(uuid())
owner String @unique
balance Int @default(0)
sent Transfer[] @relationship(type: "SENT", direction: OUT)
received Transfer[] @relationship(type: "RECEIVED", direction: OUT)
}
node Transfer {
id String @id @default(uuid())
amount Int
from Account @relationship(type: "SENT", direction: IN)
to Account @relationship(type: "RECEIVED", direction: IN)
}Generate the client inside src/ so the Nest build compiles it:
{
"schema": "./schema.cyphra",
"migrations": "./migrations",
"generate": "./src/cyphra.gen.ts"
}npx cyphra dev # local Neo4j 5 in Docker, writes .env
npx cyphra migrate dev --name init # constraints for @id and @unique
npx cyphra generate # writes src/cyphra.gen.tsFor an existing database, put NEO4J_URI, NEO4J_USERNAME and NEO4J_PASSWORD in .env
instead of running cyphra dev.
Register CyphraModule
import { CyphraModule } from "@cyphra/nestjs";
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { AccountsModule } from "./accounts/accounts.module.js";
import { createClient } from "./cyphra.gen.js";
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
CyphraModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) =>
createClient({
uri: config.getOrThrow("NEO4J_URI"),
user: config.getOrThrow("NEO4J_USERNAME"),
password: config.getOrThrow("NEO4J_PASSWORD"),
}),
}),
AccountsModule,
],
})
export class AppModule {}- The client is a singleton: one driver and one connection pool for the whole app.
- The module is global by default, so feature modules inject the client without importing it.
getOrThrowstops startup with a clear error when a variable is missing.- Without
ConfigService,CyphraModule.forRoot({ client: () => createClient({ … }) })does the same.
Inject the client into a service
import { InjectCyphra } from "@cyphra/nestjs";
import { Injectable } from "@nestjs/common";
import type { Db } from "../cyphra.gen.js";
@Injectable()
export class AccountsService {
constructor(@InjectCyphra() private readonly db: Db) {}
open(owner: string, balance = 0) {
return this.db.account.create({ data: { owner, balance } });
}
list() {
return this.db.account.findMany({ orderBy: { owner: "asc" } });
}
}Db is the client type exported by the generated file: this.db.account.findMany(…), $cypher
and the rest are fully typed. The injection token is getCyphraToken(), for moduleRef.get or the
inject list of a factory provider.
Make a method transactional
import { InjectCyphra, Transactional } from "@cyphra/nestjs";
import { BadRequestException, Injectable } from "@nestjs/common";
import type { Db } from "../cyphra.gen.js";
import { LedgerService } from "./ledger.service.js";
@Injectable()
export class AccountsService {
constructor(
@InjectCyphra() private readonly db: Db,
private readonly ledger: LedgerService,
) {}
@Transactional()
async transfer(from: string, to: string, amount: number) {
const debited = await this.db.account.update({
where: { owner: from },
data: { balance: { decrement: amount } },
});
await this.db.account.update({
where: { owner: to },
data: { balance: { increment: amount } },
});
await this.ledger.record(from, to, amount); // same transaction
if (debited.balance < 0) throw new BadRequestException(`Insufficient funds on ${from}.`);
}
}While transfer runs, every query made through an injected client, here and in LedgerService,
goes to the same write transaction. It commits when the method resolves; when it throws, nothing is
written, including the ledger entry. See How @Transactional() works.
Add a health check
import { CyphraHealthIndicator } from "@cyphra/nestjs";
import { Controller, Get } from "@nestjs/common";
import { HealthCheck, HealthCheckService } from "@nestjs/terminus";
@Controller("health")
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly cyphra: CyphraHealthIndicator,
) {}
@Get()
@HealthCheck()
check() {
return this.health.check([() => this.cyphra.isHealthy("neo4j")]);
}
}Import TerminusModule in the module that declares the controller. isHealthy runs RETURN 1:
GET /health answers 200 {"status":"ok","info":{"neo4j":{"status":"up"}}, …}, or 503 with
{"neo4j":{"status":"down","message":"…"}} when Neo4j does not answer within 5 seconds
(isHealthy("neo4j", { timeout: 2000 }) to change it).
Enable shutdown hooks
import "reflect-metadata";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module.js";
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();
await app.listen(process.env.PORT ?? 3000);CyphraModule closes the client ($disconnect(), which closes the Neo4j driver) when the module is
destroyed: on app.close() and, with enableShutdownHooks(), when the process receives SIGTERM
or SIGINT. Pass closeOnShutdown: false to keep a client you close yourself.
Try it
npm run build && npm run start:prod
curl -X POST localhost:3000/accounts -H 'content-type: application/json' \
-d '{"owner":"alice","balance":100}'
curl localhost:3000/accounts
# [{"id":"…","owner":"alice","balance":100}]
curl localhost:3000/health
# {"status":"ok","info":{"neo4j":{"status":"up"}},"error":{},"details":{"neo4j":{"status":"up"}}}The example app has the whole accounts API (transfers, history, error mapping) and its end-to-end tests.
How @Transactional() works
- The method runs inside
db.$transaction(…), and the transaction client is stored in anAsyncLocalStoragefor the call. The client that@InjectCyphra()injects looks there first: its model delegates (db.account, …) and$cypheruse the active transaction, so services do not passtxaround. - A
@Transactional()method called from another one, or from adb.$transactioncallback, joins the outer transaction; so doesdb.$transactionitself. The outermost one commits or rolls back. - Concurrent requests get separate transactions: the storage follows each async call chain.
- The driver may run the method again on transient errors (deadlocks, leader changes). Keep side effects outside of the database, such as emails or HTTP calls, out of it, or run them after it.
- Only the queries of the method’s connection are covered. Client members added with
$extends({ client })anddb.$client(sessions, the raw driver) are not routed to the transaction. getTransaction<Db>()returns the active transaction client (undefinedoutside of one), andisInTransaction()tells whether there is one.@Transactional()makes the method return a promise; decorateasyncmethods.- FalkorDB has no multi-statement transactions, so
@Transactional()rejects there as$transactiondoes.
Options
| Option | Default | What it does |
|---|---|---|
client (forRoot) | The client, or a function that creates it | |
useFactory (forRootAsync) | Creates the client from the providers in inject | |
inject, imports | [] | Dependencies of useFactory and the modules that provide them |
connection | "default" | Name of the client, for a second database |
isGlobal | true | Make the client injectable in every module |
closeOnShutdown | true | Call $disconnect() when the module is destroyed |
Several databases
Register each client under its own connection name, and use the same name to inject it, open a
transaction on it, or check it:
CyphraModule.forRootAsync({
connection: "analytics",
inject: [ConfigService],
useFactory: (config: ConfigService) =>
createAnalyticsClient({ uri: config.getOrThrow("ANALYTICS_NEO4J_URI"), … }),
});
constructor(@InjectCyphra("analytics") private readonly analytics: AnalyticsDb) {}
@Transactional({ connection: "analytics" })
async rebuild() { … }
this.cyphra.isHealthy("analytics", { connection: "analytics" });Testing
The module reads its configuration from ConfigService, so an end-to-end test points the
environment at a test database and boots the real AppModule:
process.env.NEO4J_URI = "bolt://localhost:7687";
process.env.NEO4J_USERNAME = "neo4j";
process.env.NEO4J_PASSWORD = "test";
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
const app = moduleRef.createNestApplication();
await app.init();
const db = app.get<Db>(getCyphraToken()); // seed or clean up with the typed client
// …
await app.close(); // closes the driverVitest compiles TypeScript with esbuild, which does not emit the constructor parameter types Nest
injects by; the example app’s vitest.config.ts compiles with tsc instead (a few lines, no extra
dependency).
Related
- Typed client and transactions, Runtime
(
db.$clientfor sessions and the raw driver) - Migrations: run
cyphra migrate deploybefore starting the app in production - Cypher how-tos, each with the Cyphra equivalent
- Next.js guide, Bun guide and tRPC guide