An enterprise-grade extension layer on top of NestJS for building secure, scalable server applications with GraphQL, REST/Swagger and MongoDB, PostgreSQL, MySQL or MariaDB.
- Quick Start
- Features Overview
- Architecture
- API-First Design
- Authentication
- Roles & Permissions
- Multi-Tenancy
- Databases
- API Tokens
- Offline Sync
- AI Assistant & MCP
- Operator Hub
- Scalability
- API Versioning
- Webhook Support
- External System Integration
- Core Modules
- Configuration
- Development
- Documentation
- License
The fastest way to get started is via the lenne.Tech CLI with the starter project:
npm install -g @lenne.tech/cli
lt server create <ServerName>
cd <ServerName>
pnpm startOr install directly as a package:
pnpm add @lenne.tech/nest-serverlt server module <ModuleName>This generates a complete module with model, inputs, resolver, controller, and service.
| Category | Features |
|---|---|
| API-First | GraphQL (Apollo Server) + REST with Swagger/OpenAPI, dual API surface from single codebase |
| Authentication | BetterAuth (IAM) with JWT, sessions, 2FA/TOTP, Passkey/WebAuthn, social login; Legacy JWT auth (opt-in); scoped API tokens for users and tenants |
| Authorization | Extensible role-based access control, field-level restrictions (also on nested types), system roles, hierarchy roles; every entry point checked, not just the route |
| Database | MongoDB (Mongoose), PostgreSQL, MySQL or MariaDB (TypeORM, Kysely or Drizzle) — per project or per model — behind one CrudService and security pipeline; tenant isolation enforced by row-level security on PostgreSQL; schema evolution and SQL migrations by the framework; advanced filtering & pagination |
| Multi-Tenancy | Header-based tenant isolation, membership management, hierarchy roles, auto-filtering, a tenant row check after every read, deactivatable tenants |
| Offline Sync | Mobile, web and desktop clients read and write offline and reconcile later: delta pull by cursor, push with conflict strategies, tombstones, client-generated ids, change hints over SSE and GraphQL — on every supported database, through the same security pipeline |
| File Handling | GridFS, S3 or filesystem storage, presigned downloads, resumable uploads via TUS protocol (up to 50 GB, S3 staging) |
| AI | AI assistant with tool registry, plan mode, confirmation policy, token budgets, conversations and SSE streaming; MCP server (/ai/mcp) with OAuth 2.1 |
| Security | Defense-in-depth: input validation, password hashing, role guard, audit fields, response filtering, security headers, SSRF guard for user-entered URLs, re-checked WebSocket subscriptions |
| Integration | SCIM support, OAuth providers, multi-provider email (Mailjet/Brevo/SMTP), webhook support via lifecycle hooks |
| Scalability | Stateless design; optional Redis and S3 for multi-replica deployments (shared rate limits, cron deduplication, GraphQL subscriptions, cache invalidation, file storage); distributed locks; graceful shutdown; query complexity analysis |
| API Versioning | NestJS-native URI/header/media-type versioning, GraphQL schema evolution with deprecations |
| DevOps | Operator Hub (/hub), health checks, database migrations (MongoDB and SQL), cron jobs, permissions reporting, system setup |
| Platform | NestJS 12, ESM package that CommonJS projects load as well; npm or vendor mode (the core copied into the project) |
The framework is built on a Module Inheritance Pattern — all core modules are designed to be extended through class inheritance in consuming projects:
// Your project extends core classes — full control via override + super()
export class UserService extends CoreUserService {
override async create(input, serviceOptions) {
// Custom pre-processing (validation, enrichment, ...)
const result = await super.create(input, serviceOptions);
// Custom post-processing (notifications, logging, ...)
return result;
}
}Why inheritance over hooks/events:
- Full control: Override methods and precisely define what happens before/after
super()calls - Selective override: Skip parts of the parent implementation entirely for custom logic
- Type safety: TypeScript inheritance ensures proper typing and IDE support
- No silent failures: No runtime event systems or hooks that can fail silently
src/core/— Reusable framework components (exported via npm, extended by projects)src/server/— Internal test/demo implementation (not exported)
Every core module supports both auto-registration (zero-config) and manual registration (full customization via extended module). New modules can be added alongside existing ones without modifying the framework.
- NestJS — Server framework
- Apollo Server — GraphQL API (optional, disable via
graphQl: false) - Mongoose — MongoDB ODM (optional peer since 12.1.0)
- PostgreSQL, MySQL or MariaDB via TypeORM, Kysely or Drizzle — optional, see Databases
- Swagger/OpenAPI — REST API documentation
- Redis and S3-compatible storage — optional, for multi-replica deployments (see Scalability)
The server follows an API-first approach where API contracts are the primary interface:
Both GraphQL and REST endpoints are served from the same codebase and business logic. The @UnifiedField() decorator generates schemas for both APIs simultaneously:
@UnifiedField({ description: 'User email address', isOptional: false })
email: string;
// → Generates: GraphQL @Field() + Swagger @ApiProperty() + class-validator checks- GraphQL Introspection — Full schema introspection for client code generation (configurable via
graphQl.introspection) - Swagger/OpenAPI — Auto-generated REST API documentation from decorators
- SpectaQL — Visual GraphQL documentation (
pnpm run docs) - Permissions Dashboard — Interactive HTML report of all endpoints, roles, and security checks (
/permissions)
- Custom scalars:
Date,DateTime,JSON,Any - WebSocket subscriptions with authentication
- Query complexity analysis (DoS prevention)
- File upload support via
graphql-upload - Automatic enum registration
NestJS provides built-in API versioning support with multiple strategies. Projects can enable versioning for REST endpoints:
| Strategy | Example | Use Case |
|---|---|---|
| URI | /v1/users, /v2/users |
Most common, explicit in URL |
| Header | X-API-Version: 2 |
Clean URLs, version in header |
| Media Type | Accept: application/vnd.app.v2+json |
Content negotiation |
// main.ts — enable URI versioning
app.enableVersioning({ type: VersioningType.URI });
// controller — assign to version
@Controller({ path: 'users', version: '2' })
export class UsersV2Controller { ... }
// or per-route
@Get()
@Version('2')
async findAll() { ... }GraphQL APIs are evolved through schema additions and field deprecations (@deprecated) rather than versioning, following the GraphQL best practice of continuous evolution.
The framework provides webhook capabilities through two mechanisms:
BetterAuth supports hooks that intercept authentication lifecycle events. Projects can extend the BetterAuth service via the Module Inheritance Pattern to react to these events:
export class AuthService extends CoreBetterAuthService {
override async signIn(input, serviceOptions) {
const result = await super.signIn(input, serviceOptions);
// Trigger webhook after successful sign-in
await this.webhookService.dispatch('auth.sign-in', { userId: result.user.id });
return result;
}
}Authentication events that can be intercepted include: sign-in, sign-up, sign-out, session creation, token refresh, email verification, 2FA verification, and more.
Any service method can be extended to dispatch webhooks via the Module Inheritance Pattern:
export class ProjectService extends CoreProjectService {
override async create(input, serviceOptions) {
const project = await super.create(input, serviceOptions);
// Dispatch webhook on project creation
await this.webhookService.dispatch('project.created', project);
return project;
}
}This approach allows projects to add webhook dispatching to any CRUD operation or custom business logic without modifying the framework.
Two authentication systems are available — BetterAuth (recommended) and Legacy JWT auth:
Modern, session-based authentication with plugin architecture:
| Feature | Config |
|---|---|
| JWT tokens | betterAuth.jwt: true |
| Two-Factor (2FA/TOTP) | betterAuth.twoFactor: true |
| Passkey/WebAuthn | betterAuth.passkey: true |
| Social login (Google, GitHub, Apple, ...) | betterAuth.socialProviders: { ... } |
| Email verification | betterAuth.emailVerification: { ... } |
| Rate limiting | betterAuth.rateLimit: { max: 10 } |
| Cross-subdomain cookies | betterAuth.crossSubDomainCookies: true |
| Disable sign-up | betterAuth.emailAndPassword.disableSignUp: true |
Three integration patterns: zero-config, config-based, or manual (autoRegister: false).
BetterAuth provides lifecycle hooks for reacting to authentication events (sign-in, sign-up, session creation, etc.), enabling integration with external systems. See Webhook Support for details.
Passport-based JWT authentication with sign-in, sign-up, refresh tokens, and rate limiting. Runs in parallel with BetterAuth during migration. Since 11.38.0 the legacy endpoints are off unless a project opts in with auth.legacyEndpoints.enabled: true; disabled endpoints answer 410 Gone.
A built-in migration status query (betterAuthMigrationStatus) tracks progress and indicates when legacy auth can be safely disabled.
The role and permission system is designed for extensibility — from simple role checks to complex multi-tenant hierarchies.
System roles (S_ prefix) are evaluated dynamically at runtime, never stored in the database:
| Role | Purpose |
|---|---|
S_USER |
Any authenticated user |
S_VERIFIED |
Email-verified users |
S_CREATOR |
Creator of the resource |
S_SELF |
User accessing own data |
S_EVERYONE |
Public access |
S_NO_ONE |
Permanently locked |
// Method-level: who can call this endpoint?
@Roles(RoleEnum.ADMIN)
async deleteUser() { ... }
// Field-level: who can see/modify this field?
@Restricted(RoleEnum.S_SELF, RoleEnum.ADMIN)
email: string;
// Membership-based: only team members can see this field
@Restricted({ memberOf: 'teamMembers' })
internalNotes: string;Projects can define custom role hierarchies beyond the built-in roles:
// Custom hierarchy with level-based comparison
const HR = createHierarchyRoles({ viewer: 1, editor: 2, admin: 3, owner: 4 });
@Roles(HR.EDITOR) // requires level >= 2 (editor, admin, or owner)
async editDocument() { ... }Every model can override securityCheck() for fine-grained, context-aware access control:
export class Project extends CorePersistenceModel {
override securityCheck(user: any, force?: boolean): this {
// Remove sensitive fields based on user context
if (!this.hasRole(user, RoleEnum.ADMIN)) {
this.budget = undefined;
}
return this;
}
}The built-in Permissions module scans all endpoints and generates security audit reports (HTML dashboard, JSON, Markdown) showing coverage of @Roles, @Restricted, and securityCheck() across the entire API.
Full multi-tenancy support with header-based tenant isolation, membership management, and automatic data filtering:
// config.env.ts
multiTenancy: {
headerName: 'x-tenant-id',
roleHierarchy: { member: 1, manager: 2, owner: 3 },
adminBypass: true,
}
// Usage in resolvers
@Roles(DefaultHR.MANAGER)
async updateProject(@CurrentTenant() tenantId: string) { ... }- Membership validation —
CoreTenantGuardvalidates membership on every request - Hierarchy roles — Level comparison (higher includes lower), custom via
createHierarchyRoles() - Automatic data isolation — the tenant policy filters all queries by tenant context (Mongoose plugin on MongoDB, the data store and row-level security on PostgreSQL)
- Defense-in-depth — Guard validation, the tenant policy, and a tenant row check that refuses any read result containing another tenant's row
- Every transport — GraphQL subscriptions over WebSocket get the same validated tenant context, and open sockets are re-checked when rights change
- Multi-membership — Users can belong to multiple tenants with different roles
- Status management — ACTIVE, INVITED, SUSPENDED membership states
@SkipTenantCheck()— Opt out per endpoint@CurrentTenant()— Parameter decorator for validated tenant ID
A project keeps its data in MongoDB (the default), in PostgreSQL, in MySQL 8.4 / MariaDB 11.8, or in several of them, model by model — the framework's own modules (users, tenants, API tokens, AI, file metadata, locks, migrations) and Better-Auth run on each (Better-Auth on MySQL / MariaDB since 12.1.1):
// config.env.ts — PostgreSQL as the default source
database: {
url: 'postgres://app_role@db/project', // application role: owns nothing, no BYPASSRLS
ownerUrl: 'postgres://owner_role@db/project', // owner role: creates and migrates the schema
sqlEngine: 'typeorm', // or 'kysely' / 'drizzle'
},Models are registered with CorePersistenceModule.forFeature() and declared with the framework's Schema, Prop and
SchemaFactory (same names as @nestjs/mongoose). mongoose, @nestjs/mongoose and mongodb are optional peers: a
project on PostgreSQL alone installs none of them (in vendor mode it keeps them as devDependencies for the types the
vendored core imports). On MySQL and MariaDB (mysql2 plus the engine) there is no row-level security: tenant isolation
is the store's, and native access to a tenant table must filter by tenant itself; Better-Auth's tables are created in
the framework's collation utf8mb4_bin whatever the database's default. Which database to choose:
docs/choosing-a-database.md;
the rules for code: .claude/rules/persistence.md.
Opt-in bearer tokens for integrations and scripts (apiTokens configuration):
- User tokens act as their user, with global roles removed (no admin bypass through a token)
- Tenant tokens act with the lowest hierarchy role inside their own tenant (requires
multiTenancy) - Deny by default — a token is refused on every route that does not release a scope via
@ApiTokenScopes(), public routes included - Signed short-lived assertions with encrypted signing keys, a per-token rate limit, and a separate Swagger view with only the routes a token may call
Details: src/core/modules/api-token/README.md.
Opt-in (sync configuration) for apps that must work without a connection — React Native or Capacitor with SQLite,
PWAs with IndexedDB, desktop and Node clients:
- Protocol — HTTP with JSON, fully documented in docs/offline-sync-protocol.md; a client needs
fetchand nothing else - Pull by an opaque cursor that loses no change across instances, clocks and late commits; pages bounded by count and size;
410with a clear reason when a resync is needed - Push item by item with idempotent mutation ids, client-generated ids, conditional writes on
version, and the strategiesreject,lww,mergeandcustom - Tombstones for deletions, hourly purge behind a retention horizon; hints over SSE (
GET /sync/hints) and the GraphQL subscriptionsyncHint - Security — every pull and push runs through the model's
CrudService(@Restricted,securityCheck(), tenant policy, row-level security); lost access forces a resync
A model takes part with @PersistedModel({ sync: { roles, strategy } }) and @SyncService() on its service.
Details: src/core/modules/sync/README.md, client duties in
src/core/modules/sync/SECURITY.md.
An optional AI module (ai configuration) for any OpenAI-compatible model endpoint:
- Tool registry — the assistant reaches exactly the domain operations a project registers as tools, filtered by the user's roles; a tool must route through a
CrudServicewith the caller's service options, so that@RestrictedandsecurityCheck()apply - Authorization and confirmations — a tool's
authorize()checks every call before it runs (auto mode, plan mode, MCP), and plan mode authorizes the whole plan before anything runs; destructive tools ask for confirmation, mutating tools only underai.confirmation.mutating(off by default, can be enforced) - Token budgets per user and per tenant, conversations, audit log, SSE streaming, admin-editable prompt fragments
- MCP server at
/ai/mcp(Streamable HTTP) with optional OAuth 2.1 (PKCE, dynamic client registration, consent page), so MCP clients use the same tools with the same rights;tools/callapplies the admin's tool policies andauthorize(), and asks the user through MCP elicitation before a destructive tool (ai.mcp.confirmation, on by default; each user may switch it off for themselves viaPUT /ai/settingsunless the server enforces it)
Integration: src/core/modules/ai/INTEGRATION-CHECKLIST.md.
A build-free, ADMIN-only operator cockpit at /hub, enabled per environment (hub configuration): dashboard and
diagnostics, logs, request traces, query profiler, cron jobs, database and models, migrations, files, configuration,
routes and permissions, error codes, e-mail preview and mailbox, AI. Mutating actions require a confirmation keyword
and are written to an audit log. Details: src/core/modules/hub/README.md.
The architecture is designed for horizontal scalability:
- Stateless request handling — No server-side session state in the process (JWT, or Better-Auth sessions in the database)
- Optional central infrastructure — with
redisconfigured, rate limits hold across replicas, cron jobs run once per tick (BullMQ), GraphQL subscriptions reach every replica and tenant-cache and IAM role-cache invalidations are broadcast; withs3configured, files and resumable uploads live in shared storage. Without the configuration every feature keeps its process-local behaviour - Redis outages — Redis unreachable at boot is a warning, not a failed start, and
CoreRedisService.isReady()reports the connection. Rate limits, cron leases, the MCP session registry and the tenant broadcast fall back to process-local behaviour; GraphQL subscriptions and resumable uploads (TUS) have no fallback: new subscriptions fail, published events are dropped with a warning, and uploads fail until Redis answers. Subscriptions on the shared subscriber (tenant-cache and IAM role-cache invalidation, GraphQL subscriptions) are established again after every reconnect, also when the first attempt failed at boot - Cron schedules survive a Redis restart — the BullMQ schedules live in Redis; when Redis loses them (a restart without persistence, a FLUSHDB, an eviction), every replica registers the missing ones again after its reconnect and on a 60-second check. A tick that fell due while a schedule was missing is not run
- Distributed locks — migrations, cron leases and the initial admin setup are serialized across instances, on MongoDB or SQL
- Graceful shutdown —
installGracefulShutdown(app)withshutdownDelayMslets a load balancer deregister the instance before it closes - Request-scoped isolation —
AsyncLocalStorage-basedRequestContextensures safe concurrent request processing without shared mutable state - Query complexity analysis — Configurable complexity limits prevent expensive GraphQL queries from consuming excessive resources
- Connection pooling — Managed by the Mongoose/MongoDB driver and by one pool per SQL source
BetterAuth supports OAuth integration with external identity providers (Google, GitHub, Apple, Discord, and more) via the socialProviders configuration.
Built-in SCIM (System for Cross-domain Identity Management) filter parsing and MongoDB query conversion for enterprise identity management:
scimToMongo('userName eq "Joe" and emails[type eq "work"]')
// → MongoDB: { $and: [{ userName: 'Joe' }, { emails: { $elemMatch: { type: 'work' } } }] }Supported operators: eq, co, sw, ew, gt, ge, lt, le, pr, aco, and, or.
Pluggable email provider abstraction with support for:
- Mailjet — API-based transactional email
- Brevo — API-based transactional email (formerly Sendinblue)
- SMTP — Standard SMTP via Nodemailer
All providers use the same EmailService interface with EJS template engine and locale-aware template resolution.
The Module Inheritance Pattern ensures any core module can be extended to integrate with external systems — override service methods to add API calls, event publishing, webhook dispatching, or data synchronization without modifying the framework. See also Webhook Support.
| Module | Purpose |
|---|---|
| AI | AI assistant with tool registry, budgets, conversations and an MCP server with OAuth 2.1 |
| ApiToken | Scoped user and tenant tokens, deny by default |
| Auth | Legacy JWT authentication with Passport strategies (opt-in) |
| BetterAuth | Modern auth (2FA, Passkey, Social, sessions, lifecycle hooks) on MongoDB or PostgreSQL |
| User | User management, profile, roles, verification |
| Tenant | Multi-tenancy with membership and hierarchy roles |
| File | File upload/download with GridFS, S3 or filesystem storage |
| Tus | Resumable file uploads via tus.io protocol (up to 50 GB) |
| ErrorCode | Centralized error codes with unique identifiers |
| HealthCheck | REST (/health-check) and GraphQL health monitoring, per database source |
| Hub | ADMIN-only operator cockpit at /hub |
| Migrate | Migrations for MongoDB and SQL with distributed locking for cluster deployments |
| Permissions | Security map report: routes, roles and @Restricted fields (HTML, JSON, Markdown) |
| Sync | Offline sync for mobile, web and desktop clients: pull, push, conflicts, tombstones, hints |
| SystemSetup | Initial admin creation for fresh deployments |
Abstract base service providing a complete CRUD pipeline with built-in security:
export class ProjectService extends CrudService<Project> {
// Inherits: find, findOne, create, update, delete
// With: input validation, field selection, security checks, population
}Advanced querying with comparison operators (eq, ne, gt, in, contains, regex, ...), logical operators (AND, OR), pagination, sorting, and GraphQL-driven population.
Defense-in-depth security architecture with three layers:
Layer 1: Guards & Middleware
@Roles()— Method-level authorization (includes JWT auth automatically)@Restricted()— Field-level access control with process type support (INPUT/OUTPUT)- System roles —
S_USER,S_VERIFIED,S_CREATOR,S_SELF,S_EVERYONE,S_NO_ONE
Layer 2: CrudService Pipeline
- Input validation — MapAndValidatePipe with whitelist checking
@UnifiedField()— Single decorator for GraphQL, Swagger, and validationsecurityCheck()— Resource-level security on model instances
Layer 3: Data Layer (Safety Net) — the same policies on every database: as Mongoose plugins on MongoDB, in the data store on SQL
- Password policy — Automatic password hashing
- Role guard — Prevents unauthorized role escalation at DB level; system roles can never be stored
- Audit fields — Automatic
createdBy/updatedBytracking - Tenant isolation — Automatic tenant filtering, plus a tenant row check after every read and row-level security on PostgreSQL
Interceptor Chain:
- ResponseModelInterceptor — Plain objects to CoreModel conversion
- TranslateResponseInterceptor — Multi-language support via
Accept-Language - CheckSecurityInterceptor — Executes
securityCheck()and removes secret fields - CheckResponseInterceptor — Enforces
@Restricted()field-level filtering
Multi-provider email service (Mailjet, Brevo, SMTP) with EJS template engine and locale-aware template resolution.
Configuration is managed via src/config.env.ts with environment-based profiles (development, local, production):
export const config = {
local: {
port: 3000,
graphQl: { driver: 'apollo' },
mongoose: { uri: 'mongodb://localhost/my-app' }, // or: database: 'postgres://…' (see Databases)
betterAuth: { secret: 'my-secret', jwt: true, twoFactor: true },
multiTenancy: { roleHierarchy: { member: 1, manager: 2, owner: 3 } },
},
};- Presence implies enabled:
rateLimit: {}enables with defaults,undefinedstays disabled - Boolean shorthand:
jwt: trueenables with defaults,{ expiresIn: '1h' }customizes
Three methods to override configuration:
- Direct —
process.env.PORTinconfig.env.ts - JSON —
NEST_SERVER_CONFIGenvironment variable (deep merge) - Prefixed —
NSC__EMAIL__DEFAULT_SENDER__NAMEforemail.defaultSender.name
Requirements: Node.js >= 22.15, pnpm 11, MongoDB and Docker for the e2e suite (the Redis, S3, PostgreSQL, MySQL and MariaDB test containers start automatically)
# Install dependencies
pnpm install
# Start in development mode
pnpm run start:dev
# Run tests (Vitest: unit + e2e, the e2e suite on MongoDB and on PostgreSQL)
pnpm test
# Run tests with coverage
pnpm run test:cov
# Everything a release needs: audit, format, lint, type checks, tests, build, module-format checks
pnpm run check
# Lint (oxlint) & format (oxfmt)
pnpm run lint
pnpm run format
# Build
pnpm run build
# Generate documentation
pnpm run docsThe starter project includes a production-ready multi-stage Dockerfile. It works both as a standalone project and inside a monorepo created with lt fullstack init:
# Standalone
docker build -t api .
docker run -e NSC__MONGOOSE__URI=mongodb://host:27017/mydb -p 3000:3000 api
# Monorepo (build context = monorepo root)
docker build --build-arg API_DIR=projects/api -t api .The docker-entrypoint.sh runs database migrations before starting the server. On MongoDB the migration store reads NSC__MONGOOSE__URI; on SQL, createMigrationStore() connects with the owner URL and keeps its state in lt_migrations.
Link into a consuming project for local development:
# In nest-server
pnpm run watch
# In your project
pnpm run link:nest-server # pnpm link /path/to/nest-server
pnpm run unlink:nest-server # pnpm unlink @lenne.tech/nest-server && pnpm installMAJOR.MINOR.PATCH — MAJOR mirrors NestJS version, MINOR = breaking changes, PATCH = non-breaking improvements.
- Request Lifecycle — Complete request pipeline, security architecture, interceptor chain
- Choosing a Database — MongoDB, PostgreSQL, MySQL/MariaDB or several, and which SQL engine
- Native Driver Security — What native database access bypasses, and the safe alternatives
- process() Performance — The CrudService pipeline on hot paths, subdocument arrays
- Framework API — Generated reference of interfaces,
CoreModule.forRoot()and CrudService methods - Security Overrides — Read this: pnpm
overrides:are not inherited from this package, so two known-vulnerable transitive deps need an entry in your project - Migration Guides — Version upgrade instructions
- Starter Project — Reference implementation
- CLI — Code generation tools
- NestJS Documentation — Framework docs
Many thanks to the developers of NestJS and all the developers whose packages are used here.
MIT - see LICENSE