NestJS Drizzle CRUD quick start
Build NestJS Drizzle CRUD endpoints for one table. Define the schema, configure the module, add an empty service and call it from a controller.
To build NestJS Drizzle CRUD endpoints with nestjs-drizzle-crud, you define a Drizzle table,
call DrizzleCrudModule.forRoot once, write an empty service class that extends
SqlBaseCrudService, bind it to the table with forFeature, and call its methods from a
controller. The result is a users API with list, get, create, update and delete routes, plus
filtering, sorting and pagination from the query string.
What you need first
Node 20 or later and a PostgreSQL database you can reach through a DATABASE_URL. The steps use
PostgreSQL; for MySQL or SQLite, follow
the matching tab in Installation at step 4.
How do I go from an empty project to CRUD endpoints?
Install the package and the PostgreSQL driver
pnpm add @avytrix/nestjs-drizzle-crud drizzle-orm postgres@nestjs/common, @nestjs/core and reflect-metadata come with the Nest project. See
Install NestJS with Drizzle ORM for the full peer list.
Define the Drizzle table
import { pgTable, serial, timestamp, varchar } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: serial("id").primaryKey(),
name: varchar("name", { length: 100 }).notNull(),
email: varchar("email", { length: 255 }).notNull().unique(),
created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updated_at: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
deleted_at: timestamp("deleted_at", { withTimezone: true }),
});Create the table in your database with your usual migration tool (drizzle-kit, for example).
The created_at, updated_at and deleted_at keys are not decoration. Soft delete and
timestamps are on by default, and the package looks for columns under exactly those keys in the
table object. Matching them means the service needs no config.
camelCase keys need config
With createdAt: timestamp("created_at") the key is createdAt, so name it in forFeature:
config: { softDelete: { column: "deletedAt" }, timestamps: { createdAt: "createdAt", updatedAt: "updatedAt" } }.
A key the table does not have stops the app at startup with a message that names the key to
use. A table with no deleted_at needs softDelete: { enabled: false }. See
Soft delete and Timestamps.
Configure the module once
import { Module } from "@nestjs/common";
import { DrizzleCrudModule } from "@avytrix/nestjs-drizzle-crud";
import * as schema from "./db/schema";
import { UsersModule } from "./users/users.module";
@Module({
imports: [
DrizzleCrudModule.forRoot({
dialect: "postgresql",
connectionString: process.env.DATABASE_URL,
schema,
}),
UsersModule,
],
})
export class AppModule {}forRoot registers the module globally, so every feature module can use the connection. Because
the module built the connection from connectionString, it also closes it on shutdown. Call
app.enableShutdownHooks() in main.ts so that happens on SIGTERM too.
Write an empty service
import { type CrudFilter, SqlBaseCrudService } from "@avytrix/nestjs-drizzle-crud";
import type { users } from "../db/schema";
import type { CreateUserDto, UpdateUserDto } from "./users.dto";
export type User = typeof users.$inferSelect;
export class UsersService extends SqlBaseCrudService<
User,
CreateUserDto,
UpdateUserDto,
CrudFilter
> {}export class CreateUserDto {
name!: string;
email!: string;
}
export class UpdateUserDto {
name?: string;
email?: string;
}The four type parameters are the row type, the create DTO, the update DTO and the filter type.
All four are required. CrudFilter accepts every filter the package understands.
Keep the service empty
No @Injectable(), no constructor, no injected db. forFeature builds the service and hands
it its config, so a constructor parameter or a provider entry breaks registration. Override the
protected hooks (validateCreate, beforeCreate and so on) when you need custom logic.
Bind the service to its table
import { Module } from "@nestjs/common";
import { DrizzleCrudModule } from "@avytrix/nestjs-drizzle-crud";
import { users } from "../db/schema";
import { UsersController } from "./users.controller";
import { UsersService } from "./users.service";
@Module({
imports: [
DrizzleCrudModule.forFeature([{ service: UsersService, table: users }]),
],
controllers: [UsersController],
})
export class UsersModule {}forFeature provides and exports UsersService. Do not also list it under providers: Nest
would then build its own copy with no config.
Call the service from a controller
import {
Body,
Controller,
Delete,
Get,
NotFoundException,
Param,
ParseIntPipe,
Patch,
Post,
Query,
} from "@nestjs/common";
import { CreateUserDto, UpdateUserDto } from "./users.dto";
import { UsersService } from "./users.service";
@Controller("users")
export class UsersController {
constructor(private readonly users: UsersService) {}
// ?name[iContains]=ali&sortBy=-created_at&page=2&limit=10
@Get()
findAll(@Query() query: Record<string, unknown>) {
const q = this.users.parseQuery(query);
return this.users.findAll(q.filters, q.pagination, q.options);
}
@Get(":id")
async find(@Param("id", ParseIntPipe) id: number) {
const user = await this.users.find(id);
if (!user) throw new NotFoundException(`User ${id} not found`);
return user;
}
@Post()
create(@Body() dto: CreateUserDto) {
return this.users.create(dto);
}
@Patch(":id")
update(@Param("id", ParseIntPipe) id: number, @Body() dto: UpdateUserDto) {
return this.users.update(id, dto);
}
@Delete(":id")
remove(@Param("id", ParseIntPipe) id: number) {
return this.users.softDelete(id);
}
}Import the DTOs as values, not with import type: Nest reads the runtime class through decorator
metadata. find returns null for a missing row, so the controller turns that into a 404 itself.
update and softDelete throw a 404 on their own.
ParseIntPipe fits because id is a serial column. For a uuid key use ParseUUIDPipe; see
Primary keys.
Try it
curl -X POST localhost:3000/users -H 'content-type: application/json' \
-d '{"name":"Alice","email":"alice@example.com"}'
curl -g 'localhost:3000/users?name[iContains]=ali&sortBy=-created_at'
curl -X PATCH localhost:3000/users/1 -H 'content-type: application/json' -d '{"name":"Alicia"}'
curl -X DELETE localhost:3000/users/1The list route answers with the findAll envelope:
{
"data": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"created_at": "2026-01-01T09:00:00.000Z",
"updated_at": "2026-01-01T09:00:00.000Z",
"deleted_at": null
}
],
"total": 1,
"page": 1,
"limit": 20
}A second POST with the same email is a 409, because the unique violation becomes a
DuplicateEntityException. After the DELETE, the row is soft deleted: it disappears from the
list and from GET /users/1, and restore(1) would bring it back.
What did I get?
UsersService inherits every method in CRUD operations, typed against
User. The ones this controller did not use yet:
| Method | What it does |
|---|---|
findOne(where) | First row matching an equality object, such as { email } |
count(filters) / exists(id) | Count matching rows, or check one id |
findByCursor(filters, pagination) | Keyset pagination with an opaque nextCursor |
restore(id) / forceDelete(id) | Bring a soft deleted row back, or remove it for good |
delete(id) | Hard delete of a live row |
upsert(dto, upsert) | Insert, or update on a unique key conflict |
massCreate, massUpdate, massSoftDelete, massRestore, massDelete | One transaction for a list of rows or ids |
To skip the controller entirely, the controller factory generates these routes, bulk and trash routes included.
Common questions
Soft delete is on by default and the table has no column under the key deleted_at. Name your key with softDelete: { column: "deletedAt" } in forFeature, or turn it off with softDelete: { enabled: false }.
No. DrizzleCrudModule.forFeature creates the service with a factory and passes its config to the constructor. Adding a constructor parameter or a providers entry for it breaks that.
In this controller it calls softDelete, which sets deleted_at and hides the row from reads. Call delete for a hard delete of a live row, or forceDelete to remove a row whether it is soft deleted or not.
Everything parseQuery reads: column filters such as name[iContains]=ali, sortBy, page, limit, fields, with and more. Unknown columns are a 400.
Next steps
CRUD operations
Every method the service inherits, what it returns and which exception it throws.
Filtering
Operators, groups and relation filters, from code or from the query string.
Allowlists
Limit which columns a caller may filter, sort, select and write before you go live.
Need a team?
Avytrix Technologies maintains this library and builds NestJS and Drizzle backends for clients. See what they can take on.
Install NestJS with Drizzle ORM
Set up NestJS with Drizzle ORM. Install nestjs-drizzle-crud with its four peers, then the driver for PostgreSQL, MySQL or SQLite.
CRUD operations with Drizzle in NestJS
The Drizzle ORM NestJS CRUD methods every service inherits, from find and findAll to create, update, softDelete and mass writes, with errors.