23
loading...
This website collects cookies to deliver better user experience
npm init -y
to create a default package.json file.npm install express express-rate-limit
npm start
command...
"scripts": {
"start": "node index.js"
},
...
// express import
const express = require('express')
// express initialization
const app = express()
const PORT = 3000
// generic GET route that we will use for the tests
app.get('/', function (req, res) {
return res.send('Hello World')
})
// server initialization
app.listen(PORT, () => {
console.log(`server started on port ${PORT}`)
})
npm start
(or node index.js
if you jumped the package.json step) it should display that message indicating that the application is working:localhost:3000
in the "/" route it will display the Hello World
that we configured.use
function from express to add a middleware or request handler in the root of our api to wrap it entirely.// /index.js
const express = require('express')
const rateLimit = require('express-rate-limit')
// ...
// /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: 2 // limit each IP to 2 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}`)
})
Add a "message" property inside the object passed as param for the rateLimit
function
const apiRequestLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 2, // limit each IP to 2 requests per windowMs
message: "Your limit exceeded"
})
Add a handler function to process the failure case:
const apiRequestLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 2, // limit each IP to 2 requests per windowMs
handler: function (req, res, /*next*/) {
return res.status(429).json({
error: 'You sent too many requests. Please wait a while then try again'
})
}
})
const apiRequestLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 2, // limit each IP to 2 requests per windowMs
handler: function (req, res, next) {
applyFeesForConsumer()
next()
}
})