Skip to content

Instantly share code, notes, and snippets.

@Rajdeep-Das
Created May 22, 2023 15:42
Show Gist options
  • Save Rajdeep-Das/5b286205cc056956ad0996c510829943 to your computer and use it in GitHub Desktop.
Save Rajdeep-Das/5b286205cc056956ad0996c510829943 to your computer and use it in GitHub Desktop.
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient();
app.get('/api/endpoint', (req, res) => {
const ipAddress = req.ip;
client.incr(ipAddress, (err, requestCount) => {
if (err) {
console.error('Error:', err);
return res.status(500).json({ message: 'Internal Server Error' });
}
if (requestCount > 10) {
return res.status(429).json({ message: 'Rate limit exceeded. Please try again later.' });
}
// Your logic for the protected endpoint goes here
res.json({ message: 'Success!' });
});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment