Angular applications frequently need client-side IDs — for reactive form controls, optimistic UI updates, NgRx actions, and temporary entity keys before a server round-trip. The browser’s built-in crypto.randomUUID() covers UUID v4 with zero dependencies. For UUID v7’s time-sortable prefix, the uuid npm package works in Angular without any configuration. See UUID in JavaScript for the broader ecosystem context.
UUID service with DI
// uuid.service.ts
import { Injectable } from '@angular/core';
import { v7 as uuidv7 } from 'uuid';
@Injectable({ providedIn: 'root' })
export class UuidService {
/** Returns a time-sortable UUID v7 string. */
generate(): string {
return uuidv7();
}
/** UUID v4 via the browser's built-in CSPRNG — no dependency needed. */
generateV4(): string {
return crypto.randomUUID();
}
}
Providing UUID generation through Angular’s DI system — rather than calling uuidv7() directly in components — makes the factory injectable and testable. In unit tests, override the provider with a spy returning a fixed value so test assertions are not fragile. See UUID Testing Strategies.
Reactive form control IDs
// items.component.ts
import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { UuidService } from './uuid.service';
@Component({ selector: 'app-items', templateUrl: './items.component.html' })
export class ItemsComponent {
form = new FormGroup({ items: new FormArray([]) });
constructor(private uuid: UuidService) {}
get items() { return this.form.get('items') as FormArray; }
addItem() {
this.items.push(new FormGroup({
id: new FormControl(this.uuid.generate()), // UUID v7 — stable client key
name: new FormControl(''),
}));
}
}
UUID v7 is preferred over v4 here because the timestamp prefix means items added in the same session sort in insertion order — useful when the list is synced back to the server. See UUID v4 vs v7.
NgRx — UUID as action correlation ID
// items.actions.ts
import { createAction, props } from '@ngrx/store';
export const addItem = createAction(
'[Items] Add Item',
props<{ correlationId: string; name: string }>()
);
// items.component.ts
this.store.dispatch(addItem({
correlationId: this.uuid.generate(), // trace this action through effects
name: 'New item',
}));
A UUID correlation ID on every dispatched action makes it straightforward to match actions to their effect responses, log side effects, and trace optimistic updates. This pattern mirrors idempotency keys in API design — see UUID as Idempotency Keys.
Typed ID brand for compile-time safety
// types.ts
export type ItemId = string & { readonly _brand: 'ItemId' };
export const toItemId = (raw: string): ItemId => raw as ItemId;
// usage
const id: ItemId = toItemId(this.uuid.generate());
Branded types catch accidental ID mix-ups at compile time with zero runtime cost. The full pattern including Zod validation is covered in TypeScript UUID Types.
Angular Universal / SSR
Angular Universal renders pages server-side in Node.js. crypto.randomUUID() is available globally in Node 19+. For earlier Node versions:
import { randomUUID } from 'node:crypto';
// or keep using the uuid package — works in both environments
import { v7 as uuidv7 } from 'uuid';
The uuid package detects the environment and uses crypto.randomBytes in Node.js and crypto.getRandomValues in the browser automatically. See UUID in Edge Functions for the same concern in edge runtimes.
Further reading
- UUID in JavaScript — full guide
- TypeScript UUID Types — branded types and Zod
- crypto.randomUUID() browser support
- UUID v4 vs v7 — which to use
- UUID Testing Strategies
- UUID as Idempotency Keys
External references
- Angular Dependency Injection guide
- uuid npm package
- MDN — crypto.randomUUID()
- RFC 9562 — UUID standard
Frequently asked questions
How do I generate a UUID in an Angular service?
Inject a UUID factory into an Angular service: generateId(): string { return crypto.randomUUID(); }. For UUID v7, install the uuid npm package and call v7(). Providing the factory via Angular's DI system lets you swap it for a fixed value in unit tests — see UUID Testing Strategies.
Can I use crypto.randomUUID() in Angular without a polyfill?
Yes — crypto.randomUUID() is available in all modern browsers that Angular 17+ supports (Chrome 92+, Firefox 95+, Safari 15.4+). No polyfill is needed. For server-side rendering with Angular Universal, the crypto module is available natively in Node.js 19+. See crypto.randomUUID() browser support for the full compatibility table.