TypeORM is one of the most widely used TypeScript ORMs, particularly in NestJS applications. Its default UUID generation uses @PrimaryGeneratedColumn('uuid') which produces UUID v4. Switching to UUID v7 requires replacing this with @PrimaryColumn and a @BeforeInsert() hook — a two-line change with no schema migration. See UUID v4 vs v7 for the B-tree fragmentation context.
Entity with UUID v7
// order.entity.ts
import {
Entity, PrimaryColumn, Column, BeforeInsert,
CreateDateColumn, ManyToOne, JoinColumn,
} from 'typeorm';
import { v7 as uuidv7 } from 'uuid';
@Entity('orders')
export class Order {
@PrimaryColumn({ type: 'uuid' })
id: string;
@Column({ name: 'customer_id', type: 'uuid' })
customerId: string;
@Column({ length: 32 })
status: string;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@BeforeInsert()
generateId() {
if (!this.id) this.id = uuidv7();
}
}
@BeforeInsert() fires before every INSERT — assigning UUID v7 if id is not already set. The if (!this.id) guard ensures explicitly provided IDs (e.g., in fixtures or upserts) are respected. See UUID Testing Strategies for fixture patterns.
Relationship with UUID v7 foreign key
// order-item.entity.ts
import { Entity, PrimaryColumn, Column, BeforeInsert, ManyToOne, JoinColumn } from 'typeorm';
import { v7 as uuidv7 } from 'uuid';
import { Order } from './order.entity';
@Entity('order_items')
export class OrderItem {
@PrimaryColumn({ type: 'uuid' })
id: string;
@Column({ name: 'order_id', type: 'uuid' })
orderId: string;
@ManyToOne(() => Order)
@JoinColumn({ name: 'order_id' })
order: Order;
@Column()
name: string;
@BeforeInsert()
generateId() {
if (!this.id) this.id = uuidv7();
}
}
Both id and orderId are uuid columns — TypeORM handles the join as a string equality comparison. See UUID in Databases for the storage detail.
DataSource migration
// migrations/1700000000000-CreateOrders.ts
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CreateOrders1700000000000 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "orders" (
"id" uuid NOT NULL,
"customer_id" uuid NOT NULL,
"status" varchar(32) NOT NULL,
"created_at" timestamptz NOT NULL DEFAULT now(),
CONSTRAINT "PK_orders" PRIMARY KEY ("id")
)
`);
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "orders"`);
}
}
No DEFAULT uuidv7() is needed in the migration — the application layer provides the value via @BeforeInsert(). If you want the database to generate UUIDs (e.g., for raw SQL inserts), add DEFAULT uuidv7() and upgrade to PostgreSQL 18.
PostgreSQL 18 — server-side generation
// migrations/1700000000001-AddUuidV7Default.ts
export class AddUuidV7Default1700000000001 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE orders ALTER COLUMN id SET DEFAULT uuidv7()`
);
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE orders ALTER COLUMN id DROP DEFAULT`
);
}
}
With a database-level default, you can remove the @BeforeInsert() hook from the entity and replace @PrimaryColumn with @PrimaryGeneratedColumn('uuid'). TypeORM will read back the server-generated ID after INSERT via RETURNING.
Repository usage
// orders.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from './order.entity';
@Injectable()
export class OrdersService {
constructor(
@InjectRepository(Order)
private readonly repo: Repository<Order>,
) {}
async create(customerId: string, status: string): Promise<Order> {
const order = this.repo.create({ customerId, status });
return this.repo.save(order); // @BeforeInsert assigns UUID v7
}
async findById(id: string): Promise<Order | null> {
return this.repo.findOneBy({ id });
}
}
See UUID in NestJS for the full NestJS controller and ParseUUIDPipe validation pattern.
Further reading
- UUID in NestJS — TypeORM and Prisma
- UUID v7 ORM Support in 2026
- UUID in Databases — storage and indexing
- UUID v4 vs v7 — performance comparison
- Zero-Downtime UUID Migration
- TypeScript UUID Types — branded types
External references
- TypeORM — primary column documentation
- TypeORM — @BeforeInsert listener
- uuid npm package
- RFC 9562 — UUID standard
Frequently asked questions
How do I switch from @PrimaryGeneratedColumn('uuid') to UUID v7 in TypeORM?
Replace @PrimaryGeneratedColumn('uuid') with @PrimaryColumn('uuid') and add a @BeforeInsert() hook: @BeforeInsert() generateId() { if (!this.id) this.id = uuidv7(); }. No migration is needed — the PostgreSQL uuid column stores v4 and v7 identically. See UUID in NestJS for the full NestJS + TypeORM pattern.
Does TypeORM support UUIDs with MySQL and SQLite?
Yes. TypeORM maps @PrimaryColumn('uuid') to varchar(36) on MySQL and SQLite. UUID v7 strings are stored identically to v4 — the @BeforeInsert hook provides the value. For MySQL, consider binary(16) for storage efficiency — see MySQL UUID Storage Best Practices.