NestJS wraps TypeORM with a module system, dependency injection, and built-in pipes for request validation. UUID v7 integrates at the entity level with @BeforeInsert and at the controller level with ParseUUIDPipe. See UUID in TypeORM for the framework-agnostic version.

Entity definition

// orders/order.entity.ts
import {
  Entity, PrimaryColumn, Column, BeforeInsert, CreateDateColumn,
} from 'typeorm';
import { v7 as uuidv7 } from 'uuid';

@Entity('orders')
export class Order {
  @PrimaryColumn({ type: 'uuid' })
  id: string;

  @Column({ type: 'uuid', name: 'customer_id' })
  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 TypeORM save() and insert() call. The if (!this.id) guard preserves explicitly set IDs — important for seeding and testing. See UUID Testing Strategies.

Module registration

// orders/orders.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Order } from './order.entity';
import { OrdersService } from './orders.service';
import { OrdersController } from './orders.controller';

@Module({
  imports: [TypeOrmModule.forFeature([Order])],
  providers: [OrdersService],
  controllers: [OrdersController],
})
export class OrdersModule {}

Service layer

// orders/orders.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThanOrEqual } from 'typeorm';
import { Order } from './order.entity';
import { v7 as uuidv7 } from 'uuid';

@Injectable()
export class OrdersService {
  constructor(
    @InjectRepository(Order)
    private readonly repo: Repository<Order>,
  ) {}

  async create(customerId: string): Promise<Order> {
    const order = this.repo.create({ customerId, status: 'pending' });
    // @BeforeInsert assigns UUID v7 id automatically
    return this.repo.save(order);
  }

  async findById(id: string): Promise<Order | null> {
    return this.repo.findOneBy({ id });
  }

  // Time-range query using UUID v7 sort order — no secondary index needed
  async findSince(sinceMs: number): Promise<Order[]> {
    const hex = sinceMs.toString(16).padStart(12, '0');
    const lowerBound = `${hex.slice(0,8)}-${hex.slice(8,12)}-7000-8000-000000000000`;
    return this.repo.find({
      where: { id: MoreThanOrEqual(lowerBound) },
      order: { id: 'ASC' },
    });
  }
}

See UUID v7 for Cursor Pagination for the keyset pagination pattern using this lower-bound query.

Controller with ParseUUIDPipe

// orders/orders.controller.ts
import {
  Controller, Get, Post, Param, Body, ParseUUIDPipe,
} from '@nestjs/common';
import { OrdersService } from './orders.service';

@Controller('orders')
export class OrdersController {
  constructor(private readonly service: OrdersService) {}

  @Post()
  create(@Body() body: { customerId: string }) {
    return this.service.create(body.customerId);
  }

  @Get(':id')
  findOne(
    @Param('id', new ParseUUIDPipe({ version: '7' }))
    id: string,
  ) {
    return this.service.findById(id);
  }
}

ParseUUIDPipe({ version: '7' }) validates the path parameter format and UUID version before the handler runs — invalid IDs return 400 automatically. See UUID in NestJS for the broader NestJS context.

PostgreSQL 18 server default

// For PostgreSQL 18 — delegate UUID v7 generation to the database
@PrimaryColumn({
  type: 'uuid',
  default: () => 'uuidv7()',   // PG 18 built-in
})
id: string;

With default: () => 'uuidv7()', TypeORM emits DEFAULT uuidv7() in the CREATE TABLE DDL. The @BeforeInsert hook can be removed — the database generates IDs for all INSERT paths. Requires PostgreSQL 18.

Migration

// migrations/CreateOrders.ts
import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CreateOrders1700000000000 implements MigrationInterface {
  async up(qr: QueryRunner): Promise<void> {
    await qr.createTable(new Table({
      name: 'orders',
      columns: [
        { name: 'id',          type: 'uuid', isPrimary: true, default: 'uuidv7()' },
        { name: 'customer_id', type: 'uuid', isNullable: false },
        { name: 'status',      type: 'varchar', length: '32', isNullable: false },
        { name: 'created_at',  type: 'timestamptz', default: 'now()', isNullable: false },
      ],
    }));
  }

  async down(qr: QueryRunner): Promise<void> {
    await qr.dropTable('orders');
  }
}

Further reading

External references

Frequently asked questions

What is the difference between uuid-in-nestjs and uuid-in-typeorm guides?

The UUID in TypeORM guide covers TypeORM standalone (any Node.js framework). This guide covers the NestJS-specific patterns: module registration, injection-scoped repositories, request-scoped providers, and guard-based ID validation using ParseUUIDPipe. The entity definition is the same; the DI wiring differs.

How do I validate a UUID v7 path parameter in NestJS?

Use NestJS's built-in ParseUUIDPipe: @Param('id', new ParseUUIDPipe({ version: '7' })). This rejects malformed strings and non-v7 UUIDs with a 400 error before the handler runs. For v4 fallback compatibility during migration, use version: '4' or omit the version to accept any valid UUID format. See Zero-Downtime UUID Migration.