0x7d8 / NPM_RJWEB-SERVER-RATELIMIT

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Welcome to rjweb-server-ratelimit πŸ‘‹

A rjweb-server Middleware to add rate limits

Install

npm i rjweb-server-ratelimit

or

yarn add rjweb-server-ratelimit

or

pnpm add rjweb-server-ratelimit

Usage

Setting a RateLimit on a Path

const { Server } = require('rjweb-server')
const { rateLimit } = require('rjweb-server-ratelimit')

const server = new Server({
  port: 8000
}, [
  rateLimit.config({
    http: {
      message: 'Over the limit!!',
      rules: [
        {
          path: '/api',
          ignore: '/api/version',
          timeWindow: 30000,
          maxHits: 5
        }
      ]
    }
  })
])

server.path('/api', (path) => path
  .http('GET', '/', (http) => http
    .onRequest((ctr) => {
      const limit = ctr.getRateLimits()[0]

      ctr.print(`You have used ${limit.hits} / ${limit.max} of your limits, they will be reset in ${limit.resetIn}ms`)
    })
  )
)

server.start().then((res) => {
  console.log(`Server started on port ${res.port}`)
})

Using Regex

const { Server } = require('rjweb-server')
const { rateLimit } = require('rjweb-server-ratelimit')

const server = new Server({
  port: 8000
}, [
  rateLimit.config({
    http: {
      message: 'Over the limit!!',
      rules: [
        {
          path: /api|auth/g,
          timeWindow: 30000,
          maxHits: 5
        }
      ]
    }
  })
])

server.path('/api', (path) => path
  .http('GET', '/', (http) => http
    .onRequest((ctr) => {
      const limit = ctr.getRateLimits()[0]

      ctr.print(`You have used ${limit.hits} / ${limit.max} of your limits, they will be reset in ${limit.resetIn}ms`)
    })
  )
)

server.start().then((res) => {
  console.log(`Server started on port ${res.port}`)
})

Match with Arrays

Now if any of the paths in that array match it will apply the ratelimit

const { Server } = require('rjweb-server')
const { rateLimit } = require('rjweb-server-ratelimit')

const server = new Server({
  port: 8000
}, [
  rateLimit.config({
    http: {
      message: 'Over the limit!!',
      rules: [
        {
          path: [/api|auth/g, '/stats'],
          timeWindow: 30000,
          maxHits: 5
        }
      ]
    }
  })
])

server.path('/api', (path) => path
  .http('GET', '/', (http) => http
    .onRequest((ctr) => {
      const limit = ctr.getRateLimits()[0]

      ctr.print(`You have used ${limit.hits} / ${limit.max} of your limits, they will be reset in ${limit.resetIn}ms`)
    })
  )
)

server.start().then((res) => {
  console.log(`Server started on port ${res.port}`)
})

Author

πŸ‘€ 0x4096

Show your support

Give a Star if this project helped you!

πŸ“ License

Copyright Β© 2023 0x4096.
This project is MIT licensed.

About

License:MIT License


Languages

Language:TypeScript 100.0%