Registry / auth-security / koa-jwt

koa-jwt

JSON →
library4.0.4jsnpmunverified

koa-jwt is a middleware for Koa.js applications designed to authenticate HTTP requests using JSON Web Tokens (JWTs). It parses and validates JWTs typically provided in the `Authorization` header, or optionally from a cookie or a custom `getToken` function. Upon successful validation, the decoded JWT payload is exposed on `ctx.state.user` (by default) for subsequent middleware to use for authorization and access control. The current stable version is 4.0.4. Releases are driven by dependency updates (especially `jsonwebtoken`) and bug fixes, with major versions tied to Node.js support or significant internal changes. It differentiates itself by providing a streamlined, Koa-idiomatic approach to JWT authentication, leveraging Koa's async/await middleware pattern, and integrates well with `koa-unless` for path-based exclusion. It supports single or multiple secrets, including rolling secrets or mixed authentication methods (e.g., Auth0 PEM files and shared secrets).

npm install koa-jwt
INSTALL
IMPORT
SIG · KOA-JWT
K
koa-jwt
auth-securityjavascriptv4.0.4
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

jwt
import jwt from 'koa-jwt';
const { jwt } = require('koa-jwt');
This package exports a default function. For TypeScript and modern Node.js, use ESM `import`. CommonJS `require` (e.g., `const jwt = require('koa-jwt');`) is also fully supported.
Options
import type { Options } from 'koa-jwt';
Use this type to strictly define the configuration object passed to the `koa-jwt` middleware function.
Koa.Context augmentation
import type { Context } from 'koa'; // ... and koa-jwt adds ctx.state.user
The middleware augments `Koa.Context` by adding the decoded JWT payload to `ctx.state.user`. For full type safety in TypeScript, you might need to declare module augmentations in your project to extend Koa's Context type.

This quickstart demonstrates how to set up `koa-jwt` to protect routes in a Koa application, including token generation, login, public and protected endpoints, and basic error handling.

import Koa from 'koa'; import jwt from 'koa-jwt'; import Router from '@koa/router'; import bodyParser from 'koa-bodyparser'; import { sign } from 'jsonwebtoken'; const app = new Koa(); const router = new Router(); // A secret key for signing and verifying tokens. In a real app, use environment variables. const SUPER_SECRET_KEY = process.env.JWT_SECRET ?? 'your-super-secret-jwt-key'; app.use(bodyParser()); // Unprotected route for login router.post('/login', async (ctx) => { const { username, password } = ctx.request.body as { username?: string, password?: string }; if (username === 'test' && password === 'password') { // In a real app, you'd fetch user from DB and sign a token with user-specific data. const token = sign({ id: 1, username: 'test' }, SUPER_SECRET_KEY, { expiresIn: '1h' }); ctx.body = { token }; } else { ctx.status = 401; ctx.body = { message: 'Invalid credentials' }; } }); // JWT middleware protects all routes after this point, except those explicitly excluded. // For this example, we'll manually exclude /login and /public using .unless() or a custom conditional middleware. // A more robust solution often involves the 'koa-unless' package. app.use(async (ctx, next) => { if (ctx.path.startsWith('/public') || ctx.path.startsWith('/login')) { await next(); } else { return jwt({ secret: SUPER_SECRET_KEY, debug: true })(ctx, next); } }); // Error handling for JWT authentication failures app.use(async (ctx, next) => { try { await next(); } catch (err: any) { if (401 === err.status) { ctx.status = 401; ctx.body = { error: 'Protected resource, use Authorization header to get access', details: err.originalError ? err.originalError.message : err.message }; } else { throw err; } } }); // Protected route router.get('/protected', async (ctx) => { // ctx.state.user will contain the decoded JWT payload if authentication succeeded ctx.body = `Hello, ${(ctx.state as any).user.username}! This is a protected route.`; }); // Public route router.get('/public', async (ctx) => { ctx.body = 'This is a public route, no token needed.'; }); app.use(router.routes()); app.use(router.allowedMethods()); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Try POST /login with {username: "test", password: "password"} in body'); console.log('Then GET /protected with "Authorization: Bearer <token>" header'); console.log('Or GET /public without any token'); });
Debug
Known issues
breakingVersion 4.0.0 and above of `koa-jwt` require Node.js >= 8 due to the adoption of `async`/`await`. Prior versions (e.g., v3.x) required Node.js >= 7.6, and older versions (v2.x) supported Node.js < 7.6. Running on an unsupported Node.js version will lead to syntax errors or unexpected behavior.
fix
Ensure your Node.js environment is version 8 or higher. For Koa 2 with Node < 7.6, use `koa-jwt@2`. For Koa 1, use `koa-jwt@1`.
affects: >=4.0.0
breakingVersion 4.0.4 updated its underlying `jsonwebtoken` dependency from v8.5.1 to v9.0.0. This major update in `jsonwebtoken` introduces breaking changes, notably affecting the `jwt.verify` callback signature (error is now the first argument) and `jwt.decode` no longer throwing errors for invalid tokens (it returns `null` instead). While `koa-jwt` attempts to abstract this, custom `getToken` or `isRevoked` functions that directly interact with `jsonwebtoken`'s `verify` or `decode` might need adjustments. Additionally, `jsonwebtoken` v9 dropped Node.js v10 support, impacting minimum compatible Node.js versions for downstream projects.
fix
Review your custom `getToken` or `isRevoked` implementations if they directly call `jsonwebtoken` functions. Ensure your Node.js environment meets `jsonwebtoken` v9's minimum requirements (Node.js >= 12).
affects: >=4.0.4
gotchaWhen the `debug` option is set to `true` (or implicitly `false` in older versions), `koa-jwt` might expose more detailed error messages on authentication failures, including potentially sensitive information about the token or verification process. This can be a security risk in production environments by aiding attackers in probing for vulnerabilities. Since v3.2.0, when `debug` is `false`, all thrown errors have the same generic message for security reasons.
fix
Always set `debug: false` in production environments. Implement custom error handling middleware to provide generic 401 messages without exposing internal details. If `debug: true` is needed for development, ensure it's not enabled in deployed applications.
affects: *
gotchaThe middleware resolves tokens in a specific order: `opts.getToken` function, then `opts.cookie`, then the `Authorization` header. If `opts.getToken` is provided, it takes precedence. Overlooking this order can lead to unexpected token validation issues, where a token is picked from an undesired source.
fix
Be explicit about your token source. If using `opts.getToken`, ensure it correctly handles all expected scenarios and returns `null` if no token is found from its custom source, allowing fallback to cookie or header if desired. Otherwise, rely on the default order.
affects: *
gotchaIf `ctx.state.secret` is set by an earlier middleware, `koa-jwt` will use it instead of the `secret` provided in its options. This can be powerful for per-request secrets but can also lead to misconfigurations if an unintended secret is set on the context state, bypassing the middleware's configured secret.
fix
Be mindful of `ctx.state.secret`. If you intend to use a single secret, ensure no preceding middleware modifies `ctx.state.secret`. If you use dynamic secrets, carefully manage how `ctx.state.secret` is populated and its lifecycle.
affects: *
Errors
Common errors & fixes
`koa-jwt` failed to verify token: secret or public key must be provided
The `secret` option was not provided to the `koa-jwt` middleware, or `ctx.state.secret` was not set, and a token requiring verification was present.
fix
Provide a `secret` string or buffer in the `koa-jwt` middleware options, e.g., `app.use(jwt({ secret: 'your-secret' }))`. Alternatively, if using dynamic secrets, ensure a preceding middleware correctly sets `ctx.state.secret`.
TokenExpiredError: jwt expired
The JSON Web Token presented in the request has expired according to its `exp` claim.
fix
The client needs to obtain a new, valid (unexpired) JWT from your authentication endpoint. On the server side, you can catch `TokenExpiredError` specifically in your error handling middleware to return a more informative response.
JsonWebTokenError: invalid signature
The signature of the JWT does not match the computed signature, indicating the token has been tampered with or signed with a different secret than the one `koa-jwt` is using for verification.
fix
Ensure the `secret` used by `koa-jwt` on the server matches *exactly* the secret used to sign the token. Check for environmental variable mismatches, trimming issues, or different keys for different services.
`TypeError: jwt is not a function`
Incorrect import statement for `koa-jwt` in an ESM context, or attempting to `require` an ESM-only module in a CommonJS context, or incorrect destructuring of the default export.
fix
For ESM, ensure you are using `import jwt from 'koa-jwt';`. For CommonJS, `const jwt = require('koa-jwt');` is correct. Avoid `import { jwt } from 'koa-jwt';` as it is a default export.
Upgrade
Version history
4.0.4latest on npm
Audit
Dependencies
jsonwebtokenrequiredCore dependency for signing and verifying JSON Web Tokens. `koa-jwt` wraps its functionality.
koarequiredPeer dependency; `koa-jwt` is a middleware designed specifically for Koa.js applications.
Agent activity
12 hits · last 30 days
node
10
Amazon
1
OpenAI (training)
1
Resources