Skip to content

Instantly share code, notes, and snippets.

@jsonMartin
Created February 23, 2023 01:49
Show Gist options
  • Save jsonMartin/1e72d88b3875487fb2f823e759420d80 to your computer and use it in GitHub Desktop.
Save jsonMartin/1e72d88b3875487fb2f823e759420d80 to your computer and use it in GitHub Desktop.
How to rate limit in Deno Serverless scripts using "Rate Limiter Flexible" library
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { RateLimiterMemory } from 'https://dev.jspm.io/rate-limiter-flexible';
const rateLimiter = new RateLimiterMemory({
points: 2, // points available, resets after duration
duration: 10, // in seconds
});
console.log('Rate Limiter Test');
serve(async (req: any) => {
console.log('Rate Limiter Request', req);
let response;
try {
const rateLimiterRes = await rateLimiter.consume('userId', 1);
console.log('Allowed', rateLimiterRes);
response = new Response(JSON.stringify({ body: 'Allowed' }), { headers: { 'Content-Type': 'application/json' } });
} catch (err) {
console.error('Rejected', err);
response = new Response(JSON.stringify({ status: 429, body: 'Too many ' + err.consumedPoints }), { headers: { 'Content-Type': 'application/json' } });
}
return response;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment