koa-bearer-token is a middleware for Koa.js that parses bearer tokens from incoming requests, adhering to RFC6750. It extracts tokens from the `Authorization: Bearer <token>` header, `access_token` query parameter, or `access_token` in the request body. Since version 2.0.0, it also supports extracting tokens from signed or unsigned cookies. The current stable version is 2.0.2, released in August 2021, suggesting a maintenance or slow-cadence release schedule. Key differentiators include its strict RFC6750 compliance, extensive configurability for token keys and locations, and built-in TypeScript support. It integrates seamlessly with Koa applications, making it straightforward to secure API endpoints with OAuth2 bearer tokens. It requires Node.js version 12 or higher.
npm install koa-bearer-tokenVerified import paths — ran on the pinned version, not inferred.
Demonstrates setting up `koa-bearer-token` middleware with custom options, including cookie extraction and a custom request key, and then accessing the token within a Koa route handler.
Update CommonJS imports to `const { bearerToken } = require('koa-bearer-token');` and ESM imports to `import { bearerToken } from 'koa-bearer-token';`.Ensure your Node.js environment is version 12 or newer. Update Node.js or use a compatible version of the library (e.g., 1.x.x for Node < 12).
Always use `{ signed: true }` for cookie parsing and provide a `secret` to ensure cookie integrity and prevent tampering: `bearerToken({ cookie: { signed: true, secret: 'YOUR_APP_SECRET' } })`.Ensure client applications send the bearer token in only one location (header, query, body, or cookie) to avoid 400 errors. This is intended RFC compliance, not a bug.
Change the import statement from `import bearerToken from 'koa-bearer-token';` to `import { bearerToken } from 'koa-bearer-token';`.Change the CommonJS require statement from `const bearerToken = require('koa-bearer-token');` to `const { bearerToken } = require('koa-bearer-token');`.Provide a strong secret string via the `cookie.secret` option: `bearerToken({ cookie: { signed: true, secret: 'YOUR_APP_SECRET' } })`.Perform module augmentation to extend the Koa `Request` interface: `declare module 'koa' { interface Request { [myToken]?: string; } }`.