Search code examples
node.jsexpresstwilio

How to limit Twilio SMS per user account?


In a NodeJS Express app, I'm trying to use Twilio's API to apply a rate limiter per user account.

Bucket = {
  sid: 'BLSID',
  rateLimitSid: 'RKSID',
  serviceSid: 'VASID',
  accountSid: 'ACSID',
  max: 1,
  interval: 30,
  dateCreated: 2024-01-04T08:01:59.000Z,
  dateUpdated: 2024-01-04T08:01:59.000Z,
  url: 'https://verify.twilio.com/v2/Services/...'
}

I already created a rate limit and a bucket for it but when I try to send a verification

export const sendPhoneVerificationCode = async (phone, dialCode, userId) => {
  const CZECH_DIAL_CODE = '+420';

  const sendVerificationCode = await client.verify.v2
    .services(constants.VERIFY_SERVICE_SID)
    .verifications.create({
      to: `${dialCode}${phone}`,
      channel: 'sms',
      locale: dialCode === CZECH_DIAL_CODE ? 'cs' : 'en',
      rateLimits: {
        uniqueName: userId,
      },
    });

  return sendVerificationCode;
};

it returns an e:Invalid 'RateLimits' param. There is not RateLimit with UniqueName: uniqueName error. It obviously something wrong with the rateLimits param value, but I can't figure out what it is.

Is it even possible to limit the call intervals per user id?


Solution

  • Just figured out that uniqueName should the value given to the uniqueName prop when creating the rate limiter (In my case it was uniqueName: 'endUserId'). So the fix would be to send rateLimits like this:

    rateLimits: {
       endUserId: userId,
    }
    

    This limit will be checked for each individual user id.