Files
rudder-js-sdk/src/device/DeviceId.ts
T

30 lines
832 B
TypeScript
Raw Normal View History

2026-08-12 14:02:25 +03:00
/**
* Device ID provider — generates and persists a unique device identifier.
*
* Uses `crypto.randomUUID()` (available in all evergreen browsers) and
* stores the generated UUID in localStorage under `rudder_device_id`.
*/
const STORAGE_KEY = 'rudder_device_id';
/**
* Returns the stored device ID or creates a new one if none exists.
* The device ID is persisted in localStorage and survives page reloads.
*/
export function getOrCreateDeviceId(): string {
try {
const existing = localStorage.getItem(STORAGE_KEY);
if (existing) return existing;
} catch {
// localStorage unavailable — generate ephemeral ID.
}
const id = crypto.randomUUID();
try {
localStorage.setItem(STORAGE_KEY, id);
} catch {
// Storage unavailable — ID will be ephemeral for this session.
}
return id;
}