animir / node-rate-limiter-flexible

Atomic counters and rate limiting tools. Limit resource access at any scale.
ISC License
3.03k stars 157 forks source link

Rate limiter not obeying the settings I place in opts object. Renders 429 every time. #124

Closed LGmatrix13 closed 3 years ago

LGmatrix13 commented 3 years ago

Here is my route. It is built as a Nextjs API:

import { getSession } from "next-auth/client";
import prisma from "../../lib/prisma";
import { RateLimiterMemory } from "rate-limiter-flexible";

const opts = {
  points: 6, // 6 points
  duration: 1, // Per second
};

const rateLimiter = new RateLimiterMemory(opts);

export default async function handle(req, res) {
  if (req.method === "POST") {
        create(req, res);
  } else {
    res.send(`Wrong Method`);
    res.end();
  }
}

async function create(req, res) {
  try {
    await rateLimiter.consume(req.connection.remoteAddress);
    const session = await getSession({ req });
    const result = await prisma.post.create({
          data: {
            user: String(session.user.name),
            uid: String(session.user.uid),
            image: String(session.user.image),
          },
        });
        console.log(result);
        res.json(result);
        res.status(200);
        res.end();
  } catch (rejRes) {
    res.status(429);
    res.send("Too many requests");
    res.end();
  }
}

For every post request I make, a 429 is rendered. I even set points to 600000 and it would not work. Any suggestions? Thanks for creating such a great dependency!

animir commented 3 years ago

@LGmatrix13 hi, what is full rejRes error message there?

LGmatrix13 commented 3 years ago

oops, I made I mistake on my end! I didn't place it into the snippet above, but I was await ing for the response of a fetch request I commented out:

const data = await response.json();
console.log(data);

Because I removed the fetch request, I suppose it looped requests until it failed. Hence, the number of points I placed in the opts was irrelevant.

LGmatrix13 commented 3 years ago

@LGmatrix13 hi, what is full rejRes error message there?

Thanks for the fast reply! I just had some leftover code that was looping and producing too many requests. BTW, the 429 status code I mentioned was implemented on my side, not in rejRes. Sorry for any confusion!