NestJS supports Fastify as a drop-in Express replacement, offering higher throughput with the same decorator-based architecture. UUID v7 integrates at two points: Fastify’s genReqId for per-request trace IDs, and TypeORM @BeforeInsert hooks for database primary keys. See UUID in NestJS for the Express adapter version.
Setup
npm install @nestjs/platform-fastify @fastify/static fastify
npm install uuid
npm install --save-dev @types/uuid
Bootstrap with Fastify and UUID v7 request IDs
// main.ts
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { v7 as uuidv7 } from 'uuid';
import { AppModule } from './app.module';
async function bootstrap() {
const adapter = new FastifyAdapter({
// UUID v7 as Fastify request ID — encodes arrival time
genReqId: () => uuidv7(),
logger: {
level: 'info',
serializers: {
req(req) {
return { method: req.method, url: req.url, reqId: req.id };
},
},
},
});
const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter);
await app.listen(3000, '0.0.0.0');
}
bootstrap();
Interceptor: attach trace ID to response
// trace-id.interceptor.ts
import {
CallHandler, ExecutionContext, Injectable, NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class TraceIdInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const request = context.switchToHttp().getRequest();
const reply = context.switchToHttp().getResponse();
const traceId = request.id; // UUID v7 set by Fastify's genReqId
return next.handle().pipe(
tap(() => {
reply.header('X-Trace-ID', traceId);
}),
);
}
}
Register globally in AppModule:
// app.module.ts
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { TraceIdInterceptor } from './trace-id.interceptor';
@Module({
providers: [{ provide: APP_INTERCEPTOR, useClass: TraceIdInterceptor }],
})
export class AppModule {}
TypeORM entity with UUID v7 primary key
// order.entity.ts
import { Entity, Column, PrimaryColumn, BeforeInsert } 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({ type: 'decimal', precision: 10, scale: 2 })
total: number;
@Column({ default: 'pending' })
status: string;
@BeforeInsert()
generateId() {
if (!this.id) {
this.id = uuidv7();
}
}
}
Service: cursor pagination with UUID v7
// orders.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan } from 'typeorm';
import { v7 as uuidv7 } from 'uuid';
import { Order } from './order.entity';
@Injectable()
export class OrdersService {
constructor(@InjectRepository(Order) private repo: Repository<Order>) {}
async create(customerId: string, total: number): Promise<Order> {
const order = this.repo.create({ customerId, total });
// @BeforeInsert generates UUID v7 id
return this.repo.save(order);
}
async findPage(cursor?: string, limit = 20): Promise<{ orders: Order[]; nextCursor: string | null }> {
const orders = await this.repo.find({
where: cursor ? { id: MoreThan(cursor) } : {},
order: { id: 'ASC' }, // UUID v7 ASC = chronological
take: limit,
});
const nextCursor = orders.length === limit ? orders[orders.length - 1].id : null;
return { orders, nextCursor };
}
}
See UUID v7 for Cursor Pagination.
Idempotency guard
// idempotency.guard.ts
import { CanActivate, ExecutionContext, Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { validate } from 'uuid';
import { IdempotencyKey } from './idempotency-key.entity';
import { Repository } from 'typeorm';
@Injectable()
export class IdempotencyGuard implements CanActivate {
constructor(
@InjectRepository(IdempotencyKey)
private repo: Repository<IdempotencyKey>,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const key = request.headers['idempotency-key'] as string;
if (!key) return true; // Key not required for all routes
if (!validate(key)) {
throw new ConflictException('Idempotency-Key must be a valid UUID');
}
const existing = await this.repo.findOne({ where: { key } });
if (existing) {
throw new ConflictException(`Duplicate request: key ${key} already processed`);
}
await this.repo.save({ key, createdAt: new Date() });
return true;
}
}
Further reading
- UUID in NestJS — UUID v7 with TypeORM and Prisma
- UUID in TypeORM — v7 Entities and Migrations
- UUID v7 in Microservices — Trace IDs and Correlation
- UUID as Idempotency Keys
- UUID v7 for Cursor Pagination
External references
Frequently asked questions
How do I add UUID v7 request IDs in NestJS with Fastify?
Configure Fastify's built-in genReqId option to generate UUID v7 values: genReqId: () => uuidv7(). Fastify attaches this to every request as req.id. In NestJS, read it via request.id from the execution context. Set it on the response header with reply.header('X-Request-ID', request.id). UUID v7 request IDs embed the request arrival time — useful for latency debugging from logs alone.
How do I use UUID v7 as a TypeORM primary key in NestJS?
Use the @PrimaryGeneratedColumn('uuid') decorator or override with a @BeforeInsert hook: this.id = uuidv7(). The UUID column type maps to PostgreSQL's native UUID type. For UUID v7 chronological queries use ORDER BY id ASC — no createdAt sort column needed. See UUID in NestJS.
What is the difference between using UUID v7 in NestJS with Express vs Fastify?
The UUID generation logic is identical — use the uuid npm package in both. The difference is where you inject the trace ID: with Express use a middleware function; with Fastify use the genReqId config option or a Fastify hook. Fastify's lower overhead makes UUID v7 generation a smaller fraction of total request cost. NestJS interceptors work the same way in both adapters.