codedamn

Creating Express.js middleware for rate limiting

Created by Codedamn about a year ago

0

No description provided

1 Comment

    0

    const express = require('express') const path = require('path') const fetch = require('node-fetch') const redis = require('./redis-client')

    const app = express()

    app.use(express.json())

    app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')) })

    app.post('/api/post', async (req, res) => {

    // implement rate limiting
    

    const ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).slice(0,9) const requests = await redis.incr(ip)

    await redis.expire(ip, 2)

    if(requests <= 9 ) { return res.json({ "status": "ok"

    })
    

    } if(requests >=10 && requests <=15) { return res.json({ "status": "about-to-rate-limit"

    })
    }
    
    if(requests > 15) {
      return res.json({
        "status": "rate-limited"
    
    })
    }
    
    
    

    }, )

    app.listen(process.env.PUBLIC_PORT)

    @aslam111

    Sayed Aslam Shah

    @aslam111

Your comment