DEV Community

loading...

How to restrict the number of requests from a single client in express?

venkateshdharavath profile image Venkatesh Dharavath ・1 min read

We may need to restrict some clients from using our resources quite a bit. We have a middleware handy to implement this functionality called express-rate-limit. In the snippet below "max: 100" means only 100 requests per (windowMs: 60 * 60 * 1000) an hour. The message will be sent if a client tries to request after 100 requests within an hour.

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
    max: 100,
    windowMs: 60 * 60 * 1000,
    message: 'Your hourly quota for an hour has been exhausted, 
    try again after some time !',
});

app.use('/api', limiter);
Enter fullscreen mode Exit fullscreen mode

Once this middleware is added to your app, if any 101st requests come to the server with any endpoint starting with /api will be restricted. The message "Your hourly quota for an hour has been exhausted, try again after some time !" will be sent as a response. If you find this useful hit that like button and share it.

Discussion (0)

pic
Editor guide