Drizzle UUID primary keys in NestJS

Use a Drizzle uuid primary key in NestJS, or serial and bigint. The key type comes from the column; on MySQL you send the uuid on create.

A Drizzle uuid primary key works in NestJS with no extra config: declare uuid('id').primaryKey().defaultRandom() and the service reads the key type from the Drizzle column. Serial, integer and bigint keys work the same way. The only setting is primaryKey, the key of the column, which defaults to id. On MySQL, which has no RETURNING, send the uuid in the create body so the service can read the new row back.

Do not use ParseIntPipe on uuid routes

With a uuid key, route params are strings, and @Param('id', ParseIntPipe) rejects every valid request with a 400. Use ParseUUIDPipe, or service.parseId(raw), which picks the right check for the key column.

primaryKeyOptional

string

The key of the primary key column in your Drizzle table object.

Defaults to "id"

primaryKeyTypeOptional

"serial" | "bigserial" | "int" | "bigint" | "uuid"

Deprecated, no effect. The key type comes from the Drizzle column. Still accepted so existing configs compile; removed in the next major version.

Defaults to "serial"

The primary key is also the last ORDER BY column of every findAll, which keeps offset pagination stable when other sort columns tie. See pagination and sorting.

How do I use a uuid primary key?

Declare the column

db/schema.ts
import { pgTable, timestamp, uuid, varchar } from 'drizzle-orm/pg-core';

export const tags = pgTable('tags', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: varchar('name', { length: 100 }).notNull().unique(),
  deleted_at: timestamp('deleted_at', { withTimezone: true }),
});

Register the service

tags/tags.module.ts
DrizzleCrudModule.forFeature([
  { service: TagsService, table: tags, config: { timestamps: undefined } },
])

primaryKey defaults to 'id', so a uuid column under that key needs nothing more. This table has no timestamp columns, so the entity turns timestamps off.

Parse the route param as a uuid

tags/tags.controller.ts
@Get(':id')
find(@Param('id', ParseUUIDPipe) id: string) {
  return this.tags.find(id);
}

On PostgreSQL

It works fully. create inserts with RETURNING and hands back the row with the uuid the database generated.

On MySQL

MySQL has no RETURNING, so after the insert the service reads the row back by its key. For an auto-increment key it uses the driver's insertId. A uuid has no insertId, so supply the value in the create body and the service looks the row up by it:

tags/tags.seed.ts
const tag = await tagsService.create({ id: crypto.randomUUID(), name: 'urgent' });

Only uuid and other non-auto-increment keys need this. Auto-increment keys on MySQL keep using insertId.

How do I use an auto-increment key?

Declare it in Drizzle and register the service. Nothing in the config depends on the column type:

app.module.ts
DrizzleCrudModule.forFeature([
  { service: UsersService, table: users },   // serial: int4
  { service: EventsService, table: events }, // bigserial: int8
])

On PostgreSQL the created row comes back through RETURNING; on MySQL the driver reports insertId and the service reads the row back. Both return the same Promise<T>.

How do I parse the id route param?

Call service.parseId(raw). It applies the same check a Nest pipe would, chosen from the key column, and throws a 400 on bad input. service.idKind() tells you which one applies.

idKind()Key columnparseId does
"int"integer, serial, or a bigint in number modeParseIntPipe
"bigint"bigint or bigserial in bigint modeChecks the digits and returns a BigInt
"uuid"uuidParseUUIDPipe
"string"anything else, including numeric and decimalReturns the string as is

The controller factory uses the same logic for its :id routes.

What if the key is not named id?

Set primaryKey to the key of the column in your Drizzle table object:

app.module.ts
DrizzleCrudModule.forFeature([
  { service: AccountsService, table: accounts, config: { primaryKey: 'uid' } },
])

Every method that takes an id (find, update, softDelete, restore, delete and the mass variants) matches against that column.

Can different entities use different key types?

Yes. Each service reads its key type from its own table, so serial, bigserial and uuid keys can sit side by side in one forFeature call with no extra config. The methods accept the id as any, so check the type at the route with a pipe or parseId.

Are composite primary keys supported?

No. Every CRUD method assumes a single-column key (find(id), update(id, ...)). For a table with a composite key, write a custom service method that builds the where clause with raw Drizzle on this.config.db. See Define a NestJS Drizzle CRUD service.

Serial or uuid?

serial / bigserialuuid
Index sizeSmallerLarger
JoinsFasterSlightly slower
DebuggingEasy to read and compareHarder to read
Merging data from several databasesKeys can collideNo collisions
Exposed in URLsEasy to guess the next idNot guessable

For internal tables (join tables, audit logs), serial is usually fine. For rows whose ids appear in URLs or in other systems, uuid is the safer default.

Common questions

Next steps

Last updated View change history

On this page