-
Notifications
You must be signed in to change notification settings - Fork 1
koa
Eugene Lazutkin edited this page Jul 17, 2026
·
1 revision
The Koa port of the middleware family: cognito-toolkit/koa.
import {makeAuth} from 'cognito-toolkit/koa';
function makeAuth<Payload extends object = JwtPayload>(options: AuthOptions<Payload>): Auth<Payload>;
interface Auth<Payload> {
getUser: Middleware; // ctx.state[stateUserProperty] = AuthUser | null
isAuthenticated: Middleware;
hasGroup(group: string): Middleware;
hasScope(scope: string): Middleware;
isAllowed(validator: (ctx: Context, groups: string[], scopes: string[]) => boolean | Promise<boolean>): Middleware;
setAuthCookie(ctx: Context, cookieOptions?: CookieOptions): void;
stateUserProperty: string;
}
type AuthUser<Payload> = Payload & {
_token: string; // the raw JWT
setAuthCookie(ctx: Context, cookieOptions?: CookieOptions): void; // bound helper
};Options: see Middleware ports § Options. Types come from @types/koa; the payload type flows from the verifier.
import Koa from 'koa';
import Router from 'koa-router';
import {CognitoJwtVerifier} from 'cognito-toolkit';
import {makeAuth} from 'cognito-toolkit/koa';
const verifier = CognitoJwtVerifier.create({userPoolId: 'us-east-1_MY_POOL', clientId: 'my-app-client', tokenUse: 'access'});
const auth = makeAuth({verifier, setAuthCookieOptions: {secure: true}});
const app = new Koa();
app.use(auth.getUser); // authenticate every request
const router = new Router();
router.get('/open', ctx => (ctx.body = 'anyone'));
router.get('/mine', auth.isAuthenticated, ctx => (ctx.body = ctx.state.user));
router.post('/write', auth.hasScope('write'), ctx => (ctx.body = 'scoped'));
router.post('/admin', auth.hasGroup('admins'), ctx => (ctx.body = 'grouped'));
router.get(
'/read-or-write',
auth.isAllowed(async (ctx, groups, scopes) => ctx.method === 'GET' || scopes.includes('write')),
ctx => (ctx.body = 'ok')
);
app.use(router.routes()).use(router.allowedMethods());- Cookies are read and written through
ctx.cookies— no extra middleware needed. - The automatic auth-cookie refresh (via
setAuthCookieOptions) runs afterawait next(), before Koa flushes the response. - Cookie writes pass
overwrite: trueand defaultdomaintoctx.hostname(notctx.host, which may carry a port — invalid in a cookieDomain). - The former standalone package koa-cognito-middleware is a frozen re-export of this module.
Start here
Reference
Under the hood