Koa User-Agent Detection Middleware

raw JSON →
4.1.0 verified Thu Apr 23 auth: no javascript

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.

error Property 'userAgent' does not exist on type 'Context'.
cause Using `ctx.userAgent` in TypeScript after v4.0.0 without explicitly augmenting Koa's `Context` type.
fix
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>();
error TypeError: userAgent is not a function
cause Incorrectly importing `userAgent` as a default export (`import userAgent from 'koa-useragent';` or `const userAgent = require('koa-useragent');`) when it is a named export. This was a breaking change in v2.1.3 and applies to current versions.
fix
Use named imports/destructuring: import { userAgent } from 'koa-useragent'; for ESM or const { userAgent } = require('koa-useragent'); for CommonJS.
error Error: Cannot find module 'koa-useragent'
cause The `koa-useragent` package is not installed or not resolvable in the current environment.
fix
Install the package using npm: npm install koa-useragent or yarn: yarn add koa-useragent.
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.
fix 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.
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.
fix Update imports to use named destructuring: `import { userAgent } from 'koa-useragent';` or `const { userAgent } = require('koa-useragent');`
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.
fix 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.
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.
fix If Electron detection is critical, you may need to implement custom logic using the raw user-agent string or an alternative library.
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.
fix Always use named imports/requires: `import { userAgent } from 'koa-useragent';` or `const { userAgent } = require('koa-useragent');`
npm install koa-useragent
yarn add koa-useragent
pnpm add koa-useragent

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.

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.');
});