A simple redis primitives to incr() and top() user agents.
npm install @microlink/uaFirst, initialize the library passing a Redis instance:
const Redis = require('ioredis')
const redis = new Redis()
const ua = require('@microlink/ua')(redis)After that, the library offers the following methods:
-
incr(userAgent, [clientId]) — e.g.
ua.incr(req.headers['user-agent'], req.ip)
Increment the counter associated with a user agent. Only user agents with the exact shape a real browser sends are counted: a known platform (Windows, macOS, Linux, ChromeOS, Android, iOS), an engine that runs on it (Blink, WebKit, Gecko) and known browser vendor tokens only (Edge, Opera, Samsung, Yandex, Firefox, etc.). Bots, HTTP libraries, Electron apps, in-app webviews and hand-written fakes such asChrome/124.0orMac OS X 14_6are skipped without touching Redis.
WhenclientIdis provided, the same client is counted once per user agent withinwindowseconds, so a single heavy caller cannot dominate the ranking. IP addresses are normalized first: IPv6 clients are grouped by their /64 network and IPv4-mapped IPv6 (::ffff:203.0.113.1) is the same client as its IPv4. Any other string, including an empty one or one that only looks numeric, is used as given; onlynullorundefinedcount every request. Each mark is a key holding a SHA-1 of the client id and user agent that expires afterwindow; it is not anonymization, since anyone reading Redis can brute-force the client id back. Passing aclientIdrequires a Redis client that implementsdefineCommand, such as ioredis. -
top(n, { withScore }) — e.g.
ua.top(100)
Returns an array of the N ranked from top. -
flush() — e.g.
ua.flush()
Delete the counters. Client marks are kept and expire on their own afterwindow, so a client seen just before a flush is counted again once its mark expires.
The factory accepts options as a second argument:
- window — default:
86400
Seconds during which aclientIdis counted once per user agent.
const ua = require('@microlink/ua')(redis, { window: 60 * 60 })The browser check is also exported for reuse:
const { isBrowser } = require('@microlink/ua')
isBrowser('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/124 Safari/537.36') // => falsemicrolink/ua © microlink.io, released under the MIT License.
Authored and maintained by Kiko Beats with help from contributors.
microlink.io · GitHub microlink.io · X @microlinkhq

