Wednesday, January 19, 2022

limit repeated requests to public APIs

if requests are more than limits, server will block request


limt, limit remaining, and limit reset time are in response headers
if multiple users are online, current user limit won't be affected by others'
usage is tracked by ip address
//index.js
const express = require('express')
const rateLimit = require('express-rate-limit')
const app = express()

const PORT = 3000

// Create the rate limit rule
const apiRequestLimiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1 minute
    max: 3 // limit each IP to 3 requests per windowMs
})

// Use the limit rule as an application middleware
app.use(apiRequestLimiter)

app.get('/', function (req, res) {
  return res.send('Hello World')
})

app.listen(PORT, () => {
    console.log(`server started on port ${PORT}`)
})

reference:

No comments:

Post a Comment