UNPKG

@wristband/express-auth

Version:

SDK for integrating your ExpressJS application with Wristband. Handles user authentication, session management, and token management.

70 lines (69 loc) 2.15 kB
import { getSessionSync } from '@wristband/typescript-session'; /** * Executes a callback immediately before response headers are written. * * Hooks into `res.writeHead()` to run the listener once before headers are sent, * then restores the original method. Useful for deferred session flushes or * computed header values. * * @param res - Express Response object * @param listener - Function to run before headers are written * * @internal */ function onHeaders(res, listener) { const prevWriteHead = res.writeHead.bind(res); res.writeHead = function (...args) { if (!res.headersSent) { try { listener.call(res); } catch (err) { // Silent failure - if this throws, the environment is usually fundamentally broken } } // Restore original to prevent repeated hooks res.writeHead = prevWriteHead; return prevWriteHead(...args); }; } /** * Create Wristband session middleware for Express. * * @param options - Session configuration options from @wristband/typescript-session * @returns Express middleware function * * @example * ```typescript * import { createWristbandSession } from '@wristband/express-auth'; * * app.use(createWristbandSession({ * secrets: process.env.SESSION_SECRET, * cookieName: 'my-app.session', * maxAge: 3600, // 1 hour * secure: process.env.NODE_ENV === 'production' * })); * ``` */ export function createWristbandSession(options) { return (req, res, next) => { try { req.session = getSessionSync(req, res, options); req.session.enableDeferredMode(); onHeaders(res, () => { if (!res.headersSent) { try { req.session.flushSync(); } catch (err) { // Silent failure - if this throws, the environment is usually fundamentally broken } } }); next(); } catch (error) { next(error); } }; }