koa-useragent is a Koa.js middleware designed for detecting and parsing user-agent strings from incoming HTTP requests. It enriches the Koa context (`ctx`) with a `userAgent` object containing detailed information such as browser, OS, device type (mobile, desktop, bot), and version. The package is currently at version `4.1.0`, released in July 2022, and appears to maintain an active development status, although major version releases have slowed since 2020. Key differentiators include its tight integration with Koa's context, providing structured user-agent data directly for use in middleware and route handlers, and its robust TypeScript support, which has been a focus since version 2.1.0 and refined in subsequent major releases. It is built upon the well-established `useragent` library for reliable parsing.
npm install koa-useragentVerified import paths — ran on the pinned version, not inferred.
Demonstrates setting up `koa-useragent` middleware, augmenting Koa's context type for TypeScript, and accessing parsed user-agent details in a downstream middleware to respond based on client type.
For TypeScript, define an interface extending `Koa.BaseContext` and `UserAgentContext`, then use it in your Koa app instantiation, e.g., `const app = new Koa<Koa.DefaultState, MyContext>();` where `MyContext` extends both.
Update imports to use named destructuring: `import { userAgent } from 'koa-useragent';` or `const { userAgent } = require('koa-useragent');`Review the `geoIp` related types and their usage in your codebase, adapting to the new structure or definitions provided in `koa-useragent` v3 and later.
If Electron detection is critical, you may need to implement custom logic using the raw user-agent string or an alternative library.
Always use named imports/requires: `import { userAgent } from 'koa-useragent';` or `const { userAgent } = require('koa-useragent');`Extend `Koa.BaseContext` with `UserAgentContext` in a custom interface and apply it to your Koa app, e.g., `interface MyContext extends BaseContext, UserAgentContext {} const app = new Koa<Koa.DefaultState, MyContext>();`Use named imports/destructuring: `import { userAgent } from 'koa-useragent';` for ESM or `const { userAgent } = require('koa-useragent');` for CommonJS.Install the package using npm: `npm install koa-useragent` or yarn: `yarn add koa-useragent`.