Handle a Missing User-Agent Header in a Parser API

A browser identification endpoint will sometimes receive a blank or unfamiliar User-Agent. Decide on a result that clients can use before you wire a parser into application analytics.

Worked example

Parser adapter with known and unknown controls

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

function parseAgent(header) {
  const parsed = header ? new UAParser(header).getBrowser() : {};
  return { browser: parsed.name ?? null, version: parsed.version ?? null };
}

console.log(parseAgent(
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " +
  "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
));
console.log(parseAgent(undefined));

Steps

  1. Define a response schema with nullable browser and version fields. Keep the response shape the same for requests with and without the header.
  2. Install ua-parser-js in a test project if its license meets your needs. Save the example as agent.mjs, run node agent.mjs, and compare the two synthetic records.
  3. In your API, pass the request's User-Agent value to the function. Keep feature detection and account permissions independent of the output.

What to check

  • The missing-header case should return two null values. Check an unfamiliar string too, so a new client can still read the response.
  • Browsers can reduce or spoof the header. Use it as an analytics hint and check the parser library's license before adding it to a distributable app.

Inspect the synthetic browser string

References