Skip to content

express

Eugene Lazutkin edited this page Jul 17, 2026 · 1 revision

express

The Express port of the middleware family: cognito-toolkit/express.

import {makeAuth} from 'cognito-toolkit/express';

function makeAuth<Payload extends object = JwtPayload>(options: AuthOptions<Payload>): Auth<Payload>;

interface Auth<Payload> {
  getUser: RequestHandler; // req[stateUserProperty] = AuthUser | null
  isAuthenticated: RequestHandler;
  hasGroup(group: string): RequestHandler;
  hasScope(scope: string): RequestHandler;
  isAllowed(validator: (req: Request, groups: string[], scopes: string[]) => boolean | Promise<boolean>): RequestHandler;
  setAuthCookie(req: Request, res: Response, cookieOptions?: CookieOptions): void;
  stateUserProperty: string;
}

type AuthUser<Payload> = Payload & {
  _token: string; // the raw JWT
  setAuthCookie(req: Request, res: Response, cookieOptions?: CookieOptions): void; // bound helper
};

Options: see Middleware ports § Options. Types come from @types/express (CookieOptions included); the payload type flows from the verifier.

Example

import express from 'express';
import cookieParser from 'cookie-parser';
import {CognitoJwtVerifier} from 'cognito-toolkit';
import {makeAuth} from 'cognito-toolkit/express';

const verifier = CognitoJwtVerifier.create({userPoolId: 'us-east-1_MY_POOL', clientId: 'my-app-client', tokenUse: 'access'});
const auth = makeAuth({verifier});

const app = express();
app.use(cookieParser()); // only needed for the auth-cookie features
app.use(auth.getUser); // authenticate every request

app.get('/open', (req, res) => res.send('anyone'));
app.get('/mine', auth.isAuthenticated, (req, res) => res.json(req.user));
app.post('/write', auth.hasScope('write'), (req, res) => res.send('scoped'));
app.post('/admin', auth.hasGroup('admins'), (req, res) => res.send('grouped'));

Port specifics

  • Cookie reads come from req.cookies — add cookie-parser (or an equivalent) when using the cookie source or refresh; cookie writes go through res.cookie.
  • The automatic auth-cookie refresh (via setAuthCookieOptions) hooks res.writeHead, the last common gate before headers flush.
  • Cookie writes default domain to req.hostname — Express 5 keeps the port on req.host, which the cookie serializer rejects.
  • The former standalone package cognito-express-middleware is a frozen re-export of this module.

Clone this wiki locally