UUID generator · Guide

UUID Generator Angular: Creating UUIDs in Angular Apps

Angular has no UUID helper, and it does not need one — the browser provides `crypto.randomUUID()`. The one thing to plan for is that it is unavailable outside secure contexts, which includes testing over a LAN address.

A small service

Wrapping it keeps the fallback in one place and makes it easy to stub in tests:

TypeScript
@Injectable({ providedIn: 'root' })
export class UuidService {
  generate(): string {
    if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
      return crypto.randomUUID();
    }
    const b = crypto.getRandomValues(new Uint8Array(16));
    b[6] = (b[6] & 0x0f) | 0x40;   // version 4
    b[8] = (b[8] & 0x3f) | 0x80;   // variant
    const hex = [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
    return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
  }
}

The secure context requirement

crypto.randomUUID is only defined in secure contexts. https:// and http://localhost qualify; http://192.168.1.50:4200 does not — so testing on a phone against your dev server hits the fallback path.

This is why the guard above matters even though every current browser supports the API. crypto.getRandomValues has no such restriction.

SSR

Under Angular Universal the code runs in Node, where crypto is a module rather than a global. Node 19+ exposes globalThis.crypto, so the same code works; on older Node import randomUUID from node:crypto.

Guarding with isPlatformBrowser is the conventional approach when the two paths genuinely differ.

Where UUIDs are the wrong answer

For *ngFor keys, use a stable property from the data with trackBy. Generating a UUID per render creates a new key every change detection cycle and forces Angular to destroy and recreate every DOM node.

For a temporary client-side row id before the server assigns one, a UUID is a good fit — just make sure the server treats it as a client hint rather than trusting it.

Frequently asked questions

Why is crypto.randomUUID undefined in my Angular app?

You are on an insecure context, such as an http LAN address. Use https or localhost, or fall back to getRandomValues.

Do I need the uuid npm package?

Only for v5 or v7. The built-in covers v4.

Should I use a UUID for trackBy?

No. Use a stable identifier from the data, or Angular recreates the DOM on every cycle.

Ready to try it?

Open the free browser-based UUID generator and apply what you just read — no sign-up, runs locally.

Open the UUID generator tool