UNPKG

authkit-js

Version:

Express auth toolkit (JWT, Sessions with Redis, Google/GitHub OAuth) in JavaScript

31 lines (25 loc) 1.03 kB
// Minimal token bucket rate limiter per key (IP by default) function makeRateLimit(options = {}) { const capacity = options.capacity != null ? options.capacity : 60; // tokens const intervalMs = options.intervalMs != null ? options.intervalMs : 60_000; // per minute const keyFn = options.key || ((req) => (req.ip || req.connection && req.connection.remoteAddress || 'unknown')); const map = new Map(); return function rateLimit(req, res, next) { const key = keyFn(req); const now = Date.now(); let b = map.get(key); if (!b) { b = { tokens: capacity, last: now }; map.set(key, b); } // Refill const elapsed = now - b.last; const refill = (elapsed / intervalMs) * capacity; b.tokens = Math.min(capacity, b.tokens + refill); b.last = now; if (b.tokens < 1) { res.setHeader('Retry-After', '1'); return res.status(429).json({ error: 'Too Many Requests' }); } b.tokens -= 1; next(); }; } module.exports = { makeRateLimit };