-
Notifications
You must be signed in to change notification settings - Fork 1
express
Eugene Lazutkin edited this page Jul 17, 2026
·
1 revision
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.
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'));- Cookie reads come from
req.cookies— add cookie-parser (or an equivalent) when using the cookie source or refresh; cookie writes go throughres.cookie. - The automatic auth-cookie refresh (via
setAuthCookieOptions) hooksres.writeHead, the last common gate before headers flush. - Cookie writes default
domaintoreq.hostname— Express 5 keeps the port onreq.host, which the cookie serializer rejects. - The former standalone package cognito-express-middleware is a frozen re-export of this module.
Start here
Reference
Under the hood