Koa User-Agent Detection Middleware
raw JSON →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.
Common errors
error Property 'userAgent' does not exist on type 'Context'. ↓
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>(); error TypeError: userAgent is not a function ↓
import { userAgent } from 'koa-useragent'; for ESM or const { userAgent } = require('koa-useragent'); for CommonJS. error Error: Cannot find module 'koa-useragent' ↓
npm install koa-useragent or yarn: yarn add koa-useragent. Warnings
breaking Starting with v4.0.0, the automatic modification of Koa's `Context` type for `ctx.userAgent` was removed. TypeScript users must explicitly augment the `Koa.Context` or use an interface extension to correctly type `ctx.userAgent` and avoid compilation errors. ↓
breaking In v2.1.3, the primary middleware `userAgent` changed from a default export to a named export. Code relying on `import userAgent from 'koa-useragent';` or `const userAgent = require('koa-useragent');` will break. ↓
breaking Version 3.0.0 introduced breaking changes related to the `geoIp` type. If your application utilized or extended this type, it might require adjustments. ↓
breaking Version 2.0.0 removed the 'electron check' functionality. Applications that relied on specific detection for Electron environments will no longer have this out-of-the-box support. ↓
gotcha Despite a v4.0.0 changelog entry mentioning 'add default export', the recommended and documented usage for the main `userAgent` middleware remains a named export (`{ userAgent }`) for both CommonJS and ESM. Relying on a default export might lead to unexpected behavior or future breaking changes. ↓
Install
npm install koa-useragent yarn add koa-useragent pnpm add koa-useragent Imports
- userAgent wrong
import userAgent from 'koa-useragent';correctimport { userAgent } from 'koa-useragent'; - userAgent (CommonJS) wrong
const userAgent = require('koa-useragent');correctconst { userAgent } = require('koa-useragent'); - UserAgentContext
import { UserAgentContext } from 'koa-useragent';
Quickstart
import Koa, { BaseContext } from 'koa';
import { userAgent, UserAgentContext } from 'koa-useragent';
interface MyContext extends BaseContext, UserAgentContext {}
const app = new Koa<Koa.DefaultState, MyContext>();
app.use(userAgent);
app.use(async (ctx) => {
console.log('User Agent Details:', ctx.userAgent);
// Example of using user agent data:
if (ctx.userAgent.isMobile) {
ctx.body = 'Hello, Mobile User!';
} else if (ctx.userAgent.isBot) {
ctx.body = 'Hello, Bot!';
} else {
ctx.body = `Hello, ${ctx.userAgent.browser} on ${ctx.userAgent.os}!`;
}
});
const port = process.env.PORT ?? 3000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log('Try accessing with different devices/browsers.');
});