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

31 lines
816 B
TypeScript

/**
* Device ID provider — generates and persists a unique device identifier.
*
* Generates a UUID v4 and stores the generated UUID in localStorage under `rudder_device_id`.
*/
import { uuidv4 } from '../core/uuid.js';
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 = uuidv4();
try {
localStorage.setItem(STORAGE_KEY, id);
} catch {
// Storage unavailable — ID will be ephemeral for this session.
}
return id;
}