Next.js App Router distributes code across three runtimes: Edge (middleware), Node.js (Server Components, Route Handlers, Server Actions), and the browser (Client Components). UUID generation with the uuid npm package works in all three without configuration. The key practice is using UUID v7 as a correlation ID in middleware so every request — and every log line it generates — can be traced across the entire stack.

Installation

npm install uuid
npm install --save-dev @types/uuid

The uuid package is tree-shakeable. Only imported functions (v4, v7, validate, etc.) are included in the bundle. Using v7 from a Server Component or Route Handler does not add uuid to the client bundle.

Middleware — Correlation ID Injection

Inject a UUID v7 correlation ID for every request in middleware.ts:

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { v7 as uuidv7 } from 'uuid';

export function middleware(request: NextRequest) {
  // Reuse existing correlation ID if set by an upstream proxy
  const correlationId =
    request.headers.get('x-correlation-id') ?? uuidv7();

  // Clone headers and add/forward the correlation ID
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-correlation-id', correlationId);

  const response = NextResponse.next({
    request: { headers: requestHeaders },
  });

  // Echo it back in the response so clients can correlate browser logs
  response.headers.set('x-correlation-id', correlationId);
  return response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

UUID v7 gives you the request timestamp for free — parseInt(correlationId.replace(/-/g,'').slice(0,12), 16) yields the Unix millisecond when the request arrived.

Route Handlers — UUID v7 Primary Keys

// app/api/orders/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { v7 as uuidv7 } from 'uuid';
import { db } from '@/lib/db';

export async function POST(request: NextRequest) {
  const h = await headers();
  const correlationId = h.get('x-correlation-id') ?? uuidv7();

  const body = await request.json();

  // UUID v7 as primary key — time-ordered, index-friendly
  const orderId = uuidv7();

  const order = await db.query(
    `INSERT INTO orders (id, customer_id, total, correlation_id)
     VALUES ($1, $2, $3, $4)
     RETURNING *`,
    [orderId, body.customerId, body.total, correlationId],
  );

  console.log(JSON.stringify({
    correlationId,
    orderId,
    event: 'order.created',
    customerId: body.customerId,
  }));

  return NextResponse.json(order.rows[0], {
    status: 201,
    headers: { 'x-correlation-id': correlationId },
  });
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const cursor = searchParams.get('cursor');

  // Cursor pagination — UUID v7 sort = chronological
  const orders = cursor
    ? await db.query(
        'SELECT * FROM orders WHERE id > $1 ORDER BY id LIMIT 20',
        [cursor],
      )
    : await db.query('SELECT * FROM orders ORDER BY id LIMIT 20');

  const last = orders.rows.at(-1);
  return NextResponse.json({
    orders: orders.rows,
    nextCursor: orders.rows.length === 20 ? last?.id : null,
  });
}

Server Actions — UUID in Form Submissions

// app/actions/create-task.ts
'use server';

import { revalidatePath } from 'next/cache';
import { headers } from 'next/headers';
import { v7 as uuidv7 } from 'uuid';
import { db } from '@/lib/db';

export async function createTask(formData: FormData) {
  const h = await headers();
  const correlationId = h.get('x-correlation-id');

  const title = formData.get('title') as string;
  if (!title?.trim()) {
    return { error: 'Title is required' };
  }

  const taskId = uuidv7();

  await db.query(
    'INSERT INTO tasks (id, title, correlation_id) VALUES ($1, $2, $3)',
    [taskId, title.trim(), correlationId],
  );

  revalidatePath('/tasks');
  return { taskId };
}
// app/tasks/new/page.tsx
import { createTask } from '@/app/actions/create-task';

export default function NewTaskPage() {
  return (
    <form action={createTask}>
      <input name="title" placeholder="Task title" required />
      <button type="submit">Create</button>
    </form>
  );
}

Server Components — Reading Correlation IDs

// app/orders/[id]/page.tsx
import { headers } from 'next/headers';
import { notFound } from 'next/navigation';
import { validate } from 'uuid';
import { db } from '@/lib/db';

interface Props {
  params: { id: string };
}

export default async function OrderPage({ params }: Props) {
  // Validate UUID from URL before hitting the database
  if (!validate(params.id)) notFound();

  const h = await headers();
  const correlationId = h.get('x-correlation-id');

  const result = await db.query(
    'SELECT * FROM orders WHERE id = $1',
    [params.id],
  );

  if (!result.rows[0]) notFound();

  const order = result.rows[0];

  // correlationId links this page render to the request in logs
  console.log(JSON.stringify({ correlationId, event: 'order.viewed', orderId: params.id }));

  return (
    <div>
      <h1>Order {order.id}</h1>
      <p>Total: ${order.total}</p>
    </div>
  );
}

Edge Runtime Route Handlers

Route Handlers can opt into the Edge Runtime for global low-latency execution:

// app/api/events/route.ts
export const runtime = 'edge'; // Runs in V8 isolates globally

import { v7 as uuidv7 } from 'uuid'; // Works — Edge Runtime has crypto.getRandomValues()
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  const body = await request.json();

  const event = {
    id: uuidv7(),
    type: body.type,
    payload: body.payload,
    timestamp: new Date().toISOString(),
  };

  // Forward to a durable store (Upstash, PlanetScale, Neon, etc.)
  await fetch(process.env.EVENT_STORE_URL!, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(event),
  });

  return NextResponse.json({ id: event.id }, { status: 202 });
}

The Edge Runtime does not support Node.js APIs like fs or net. The uuid package uses only Web Crypto APIs and is fully Edge-compatible.

Prisma Integration

With Prisma, define UUID v7 primary keys using @default and a custom generator, or generate in application code:

// schema.prisma
model Order {
  id            String   @id @default(dbgenerated("gen_random_uuid()"))
  customerId    String
  total         Float
  correlationId String?
  createdAt     DateTime @default(now())
}
// Using UUID v7 from application code (recommended for App Router)
import { v7 as uuidv7 } from 'uuid';
import { prisma } from '@/lib/prisma';

const order = await prisma.order.create({
  data: {
    id: uuidv7(),           // UUID v7 — overrides the dbgenerated default
    customerId,
    total,
    correlationId,
  },
});

Generating UUIDs in application code (rather than dbgenerated) makes the ID available before the database round-trip — useful for optimistic UI updates and logging.

Idempotency Keys in Route Handlers

// app/api/payments/route.ts
import { v7 as uuidv7, validate } from 'uuid';
import { NextRequest, NextResponse } from 'next/server';
import { redis } from '@/lib/redis';

export async function POST(request: NextRequest) {
  const idempotencyKey = request.headers.get('idempotency-key');

  if (!idempotencyKey || !validate(idempotencyKey)) {
    return NextResponse.json(
      { error: 'Valid UUID idempotency-key header required' },
      { status: 400 },
    );
  }

  // Check cache — 24-hour idempotency window
  const cached = await redis.get(`idempotency:${idempotencyKey}`);
  if (cached) {
    return NextResponse.json(JSON.parse(cached), {
      status: 200,
      headers: { 'x-idempotent-replayed': 'true' },
    });
  }

  const body = await request.json();
  const result = await processPayment(body);

  await redis.setex(
    `idempotency:${idempotencyKey}`,
    86400, // 24 hours
    JSON.stringify(result),
  );

  return NextResponse.json(result, { status: 201 });
}

Structured Logging Pattern

Combining the middleware correlation ID with structured JSON logging gives full request traceability:

// lib/logger.ts
import { headers } from 'next/headers';

export async function getLogger() {
  const h = await headers();
  const correlationId = h.get('x-correlation-id');

  return {
    info: (event: string, data?: object) =>
      console.log(JSON.stringify({ level: 'info', correlationId, event, ...data })),
    error: (event: string, error: unknown, data?: object) =>
      console.error(JSON.stringify({
        level: 'error', correlationId, event,
        error: error instanceof Error ? error.message : String(error),
        ...data,
      })),
  };
}

// Usage in a Route Handler
export async function POST(request: NextRequest) {
  const log = await getLogger();
  log.info('order.create.start', { customerId: 'abc' });
  // ...
  log.info('order.create.complete', { orderId });
}

Every log line carries the same UUID v7 correlation ID. Log aggregators (Datadog, Loki, CloudWatch Insights) group all lines for a request with a single filter: correlationId = "018fbe3a-...".

Further Reading

External References

Frequently asked questions

Can I use UUID v7 in Next.js Server Components?

Yes. Server Components run in Node.js, which has full crypto support. Import { v7 as uuidv7 } from 'uuid' and call uuidv7() in any Server Component, Server Action, or Route Handler. The uuid package is a server-side dependency and will not be included in the client bundle unless you import it from a Client Component. See the UUID in JavaScript guide for browser-specific patterns.

Does UUID v7 work in Next.js middleware (Edge Runtime)?

Yes. Next.js middleware runs on the Edge Runtime (V8 isolates via Cloudflare Workers or Vercel Edge), which exposes the Web Crypto API including crypto.getRandomValues() and Date.now(). The uuid npm package uses both APIs — it works in middleware without any polyfill. UUID v7 is ideal for injecting correlation IDs in middleware because the timestamp is embedded in the ID.

Should I generate UUIDs in Server Components or Route Handlers?

Generate UUIDs as close to the data creation point as possible. In Route Handlers (app/api/*/route.ts), generate the UUID before the database insert. In Server Actions, generate it at the start of the action. Avoid generating a UUID in a Server Component only to pass it down as a prop to a Client Component — the UUID would change on every re-render. Use a stable source like a database ID or a URL parameter for Client Components.

How do I add a request correlation ID in Next.js middleware?

In middleware.ts, generate a UUID v7 and add it to the request headers using NextResponse.next({ request: { headers } }). The header propagates to all Route Handlers and Server Components via headers() from next/headers. Use UUID v7 so that correlation IDs are time-ordered across log entries. See the middleware section below for the complete implementation.

How do I access the correlation ID from a Server Component?

Use the headers() function from next/headers — it returns the incoming request headers including any custom headers set by middleware. Call headers().get('x-correlation-id') to read the UUID v7 correlation ID injected by middleware. This function is async in Next.js 15+: const h = await headers(); h.get('x-correlation-id').