DEV Community

Cover image for deviceFingerprint: Stable Device Buckets Without the Hype
Saiful Islam
Saiful Islam

Posted on

deviceFingerprint: Stable Device Buckets Without the Hype

A three-field key built from the user agent stops routine auto-updates from reading as new devices — and the version string is the field you have to throw away.

Caution — use it at your own risk. A user agent is user-controlled text. This is a coarse, spoofable hint for analytics and benign personalization, not authentication, fraud prevention, or a unique-person identifier. Track people only with informed consent, check the privacy rules that apply to you (including ePrivacy/GDPR and CCPA-style laws), and treat every fingerprint as an approximation. If you ship it, the consequences are yours.

The Problem

Your sign-in handler is short, readable, and wrong in a way that only shows up after a patch Tuesday.

// Stand-ins: swap these for your own store and mail sender.
declare function getKnownDevices(accountId: string): Promise<string[]>;
declare function sendNewDeviceEmail(
  accountId: string,
  ua: string
): Promise<void>;
declare function rememberDevice(accountId: string, ua: string): Promise<void>;

export async function onSignIn(request: Request, accountId: string) {
  const ua = request.headers.get("user-agent") ?? "";
  const known = await getKnownDevices(accountId);

  if (!known.includes(ua)) {
    await sendNewDeviceEmail(accountId, ua);
    await rememberDevice(accountId, ua);
  }
}
Enter fullscreen mode Exit fullscreen mode

Most days this works. Then Chrome moves from 120.0.0.0 to 121.0.0.0 in the background, and the same laptop on the same network produces a new string:

const before =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36";
const after = before.replace("120.0.0.0", "121.0.0.0");

known.includes(before); // true
known.includes(after); // false: "new device" email, same person
Enter fullscreen mode Exit fullscreen mode

One patch release becomes a support ticket. A macOS point release does the same thing. A browser that changes its UA format does it to everyone at once.

Three fixes come to mind, and each one moves the problem.

  1. Normalize the string with toLowerCase(). Case is not what changed. Chrome/120 and Chrome/121 are still two different strings, so the alert still fires.
   const key = ua.toLowerCase();
Enter fullscreen mode Exit fullscreen mode
  1. Strip the version numbers with a regex. This works for the one browser you tested. Safari puts its version in Version/, Firefox uses rv:, and OS versions keep moving. Now you own a regex that has to be updated every time a vendor changes its format.
   const key = ua.replace(/\d+\.\d+(\.\d+)*/g, "");
Enter fullscreen mode Exit fullscreen mode
  1. Hash the whole user agent. Hashing makes the key short and unreadable, but it preserves every byte of churn. Chrome/120 and Chrome/121 hash to different values, exactly as before. You have added a dependency on collision resistance to solve a problem that was never about collisions.
   const bytes = await crypto.subtle.digest(
     "SHA-256",
     new TextEncoder().encode(ua)
   );
   const key = Array.from(new Uint8Array(bytes))
     .map((b) => b.toString(16))
     .join("");
Enter fullscreen mode Exit fullscreen mode

You need one key that stays the same through routine updates and still differs when the browser or platform actually changes, and every string-level trick either keeps the noise or throws away the signal.

The shape of the fix is to let a parser split the string, then build the key from only the parts that identify a class of device:

import { UAParser } from "ua-parser-js";

export function parseUserAgent(userAgent: string) {
  const { browser, os, device } = UAParser(userAgent);
  const browserName = browser.name ?? null;
  const osName = os.name ?? null;
  const deviceType = device.type ?? null;
  return {
    fingerprint: [
      browserName ?? "unknown",
      osName ?? "unknown",
      deviceType ?? "unknown",
    ].join("|"),
    browser: browserName,
    os: osName,
    deviceType,
  };
}
Enter fullscreen mode Exit fullscreen mode

deviceFingerprint is a thin wrapper that returns just .fingerprint for callers that do not need the display fields.

The Mental Model

Think of a library card stamped with the branch, the section, and the format — never the checkout date.

  • Identity: the three stamps are the browser name, the OS name, and the device type. Joining them with | gives one readable string: Chrome|Windows|unknown.
  • Update timing: you get a fresh card each time you walk in (parseUserAgent runs on every call), but the stamps only change when you switch branch, section, or format. The checkout date — the version — never goes on the card, so an auto-update leaves the stamp unchanged.
  • Read timing: the librarian reads the card at the desk, synchronously, whenever someone asks. There is no subscription, no effect, and no stored state to go stale.

Two consequences. First, two people with the same card look identical; that is the cost of a stable class. Second, the version is not lost — it is still on the parsed object if you need it for display, but it stays out of the key.

The checkout date tells you when; the stamps tell you who.

How to Use It

Install the parser and a test runner, then copy these two files:

pnpm add ua-parser-js
pnpm add -D vitest
Enter fullscreen mode Exit fullscreen mode
src/
└── utils/
    ├── device-fingerprint.ts
    └── device-fingerprint.test.ts
package.json
Enter fullscreen mode Exit fullscreen mode

Imports below use @/, which maps to src/. Swap in whatever alias your project uses, or use relative paths the way the test file does.

src/utils/device-fingerprint.ts — the whole utility:

import { UAParser } from "ua-parser-js";

export interface ParsedUserAgent {
  /** Stable identity of the browser/device, ignoring versions. */
  fingerprint: string;
  browser: string | null;
  os: string | null;
  deviceType: string | null;
}

/**
 * Parse a user agent into a stable device fingerprint plus display-friendly
 * browser/OS/device details. Versions are intentionally dropped so routine
 * browser auto-updates do not read as a brand new device.
 */
export function parseUserAgent(userAgent: string): ParsedUserAgent {
  const { browser, os, device } = UAParser(userAgent);

  const browserName = browser.name ?? null;
  const osName = os.name ?? null;
  const deviceType = device.type ?? null;

  return {
    fingerprint: [
      browserName ?? "unknown",
      osName ?? "unknown",
      deviceType ?? "unknown",
    ].join("|"),
    browser: browserName,
    os: osName,
    deviceType,
  };
}

export function deviceFingerprint(userAgent: string): string {
  return parseUserAgent(userAgent).fingerprint;
}
Enter fullscreen mode Exit fullscreen mode

src/utils/device-fingerprint.test.ts — the contract, pinned so a dependency bump cannot quietly change your keys:

import { describe, expect, it } from "vitest";

import { deviceFingerprint, parseUserAgent } from "./device-fingerprint";

const CHROME_WINDOWS =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const CHROME_WINDOWS_UPDATED =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36";
const SAFARI_MAC =
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15";

describe("parseUserAgent", () => {
  it("extracts browser, os and device type", () => {
    const parsed = parseUserAgent(CHROME_WINDOWS);

    expect(parsed.browser).toBe("Chrome");
    expect(parsed.os).toBe("Windows");
    expect(parsed.fingerprint).toBe("Chrome|Windows|unknown");
  });

  it("ignores user agent versions", () => {
    expect(deviceFingerprint(CHROME_WINDOWS)).toBe(
      deviceFingerprint(CHROME_WINDOWS_UPDATED)
    );
  });

  it("distinguishes different browsers or platforms", () => {
    expect(deviceFingerprint(CHROME_WINDOWS)).not.toBe(
      deviceFingerprint(SAFARI_MAC)
    );
  });
});
Enter fullscreen mode Exit fullscreen mode

This is written against ua-parser-js 2.x (^2.0.10) and Vitest. The parser ships lookup tables, so pin the major version and re-run this test file when you bump it; a new detection rule can change a name and therefore your key.

Pattern 1: Count device classes without version churn

import { deviceFingerprint } from "@/utils/device-fingerprint";

type Counts = Record<string, number>;

export function bucketRequest(request: Request, counts: Counts): Counts {
  const key = deviceFingerprint(request.headers.get("user-agent") ?? "");
  return { ...counts, [key]: (counts[key] ?? 0) + 1 };
}

export const emptyCounts: Counts = {};
const next = bucketRequest(new Request("https://example.com"), emptyCounts);
Enter fullscreen mode Exit fullscreen mode

Your buckets are Chrome|Windows|unknown instead of a long tail of patch versions, so a graph of "devices this week" does not spike every time a browser auto-updates.

Pattern 2: A new-device notice that survives auto-updates

import { parseUserAgent } from "@/utils/device-fingerprint";

// Stand-ins for your own store and mailer.
declare function knownFingerprints(userId: string): Promise<string[]>;
declare function sendNotice(userId: string, label: string): Promise<void>;

export async function checkDevice(userId: string, ua: string) {
  const { fingerprint, browser, os } = parseUserAgent(ua);
  if ((await knownFingerprints(userId)).includes(fingerprint)) return;
  await sendNotice(
    userId,
    `${browser ?? "Unknown browser"} on ${os ?? "unknown OS"}`
  );
}
Enter fullscreen mode Exit fullscreen mode

The comparison uses the stable key, while the email uses the friendly fields from the same parse. Chrome 120 to 121 is silent; a switch from Windows Chrome to macOS Safari is not.

Pattern 3: Display unknown fields safely

import {
  parseUserAgent,
  type ParsedUserAgent,
} from "@/utils/device-fingerprint";

export function describe(ua: string): string {
  const parsed: ParsedUserAgent = parseUserAgent(ua);
  const parts = [parsed.browser, parsed.os, parsed.deviceType].filter(
    (value): value is string => value !== null
  );
  return parts.length > 0 ? parts.join(" on ") : "Unrecognized device";
}
Enter fullscreen mode Exit fullscreen mode

Every optional field is normalized to null, so a missing device type never leaks the literal string "undefined" into a log or a UI.

Pattern 4: Lock the stability contract in a test

import { describe, expect, it } from "vitest";

import { deviceFingerprint } from "@/utils/device-fingerprint";

describe("fingerprint contract", () => {
  it("keeps the same class across a browser update", () => {
    const v120 =
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36";
    const v121 = v120.replace("120.0.0.0", "121.0.0.0");
    expect(deviceFingerprint(v120)).toBe(deviceFingerprint(v121));
  });
});
Enter fullscreen mode Exit fullscreen mode

When a parser upgrade changes a detection rule, this test fails before your analytics buckets split in production.

❌ Do not use deviceFingerprint as a session id, an auth factor, or a unique-visitor counter. Two people on Chrome and Windows get the same value, and one person can change their user agent in a single request.

When to Use It

Read the caution at the top before you ship this. Reach for it only when all three are true:

  • You need a coarse device class, not the identity of a person.
  • Version churn would corrupt your data or spam your users with false "new device" events.
  • Collisions are harmless: two people with the same browser and OS looking identical does not break your feature.
Situation Better tool
You need a cryptographically unique device id A first-party install id with consent
You are preventing account takeover or fraud Server-side signals and behavior, not a UA string
You need exact browser versions for support The parsed browser.version, or feature detection
You want hardware-level client fingerprinting Nothing; the privacy and legal risk outweighs the value
You need high-cardinality product analytics A consented analytics SDK
You are classifying crawlers and bots Server logs or a dedicated bot-management service

The smell test: if two different people with the same laptop setup would break your feature, this utility is the wrong tool.

How It Works Under the Hood

  1. Parsing is delegated, not hand-rolled. UAParser(userAgent) returns { browser, os, device }. Writing your own regex puts you in the business of tracking every vendor's UA format; the library owns that table. The cost is a dependency and its parse tables at module load.

  2. Missing fields become null, not undefined. browser.name ?? null, os.name ?? null, and device.type ?? null give callers one predictable empty value. That matters when the result crosses a serialization boundary: JSON.stringify drops undefined properties but keeps null ones, so the shape stays identical.

  3. The key is three fields joined by |. Versions are deliberately absent. The unknown sentinel keeps the arity: a Windows Chrome desktop is Chrome|Windows|unknown, never the shorter Chrome|Windows, so a later device-type detection cannot silently reshuffle your buckets. The separator is for humans reading logs, not for security.

  4. deviceFingerprint is a one-line wrapper. Callers that only need the key can import one function; callers that need the label use parseUserAgent. Both paths run the same parse, so they cannot disagree.

  5. The cost is one parse and a few strings per call. There is no cache, no timer, and no retained reference: the UA string is borrowed for the call, three fields are normalized, and one joined string is allocated. Call it once per request or render and pass the result around instead of re-parsing in a loop.

Phase UA input browser / os / device fingerprint What changed
First request Chrome 120 on Windows Chrome / Windows / unknown `Chrome\ Windows\
Auto-update to Chrome 121 Chrome 121 on Windows Chrome / Windows / unknown {% raw %}`Chrome\ Windows\
Discarded React render Chrome 121 on Windows Chrome / Windows / unknown {% raw %}`Chrome\ Windows\
Committed render Chrome 121 on Windows Chrome / Windows / unknown {% raw %}`Chrome\ Windows\
Safari on macOS Safari 17 on macOS Safari / macOS / unknown {% raw %}`Safari\ macOS\
Spoofed UA Arbitrary text Whatever the parser finds Unpredictable Input is untrusted

The discarded render is the reason this is a pure function: a render that is thrown away computes a string nobody uses, and a committed render computes the same string again. No effect, no cleanup, no ordering bug.

Server-rendering note. On the server the string comes from the {% raw %}user-agent header; in the browser it comes from navigator.userAgent. Those are not guaranteed to match. Chromium's User-Agent Reduction freezes much of the version detail and moves it to Client Hints, so a client-side parse can return unknown where a server-side header still has detail, and mobile detection can vary. Pick one side as the source of truth for your keys and use it consistently.

Compared to built-ins. navigator.userAgentData (Client Hints) gives structured brands, platform, and mobile fields, but it is Chromium-only, needs a secure context, and server access requires an Accept-CH opt-in. It also carries version detail that this utility intentionally discards, so it does not buy stability for this use case. No built-in gives a stable, cross-browser device-class string; the library is doing the normalization work, and the three-field key is what makes the result boring enough to store.

Conclusion

The trade is stability bought by throwing information away. You give up versions and uniqueness, and in return a routine update stops looking like a new device.

  • Build the key from browser, OS, and device type; keep versions on the parsed object for display only.
  • Normalize missing fields to null and use an unknown sentinel so the key shape never drifts.
  • Pin the parser major version and test that two versions of one browser produce one fingerprint.

This belongs in coarse analytics and benign personalization. When you need to know who is at the door, the boring answer — a consented first-party id or a real session — wins every time. And use this at your own risk: it is a hint, not an identity.

Top comments (0)