Skip to content

Latest commit

 

History

History
72 lines (53 loc) · 1.74 KB

README.MD

File metadata and controls

72 lines (53 loc) · 1.74 KB

tRPC Limiter

An open source, tRPC rate limiter middleware.

Adapters

This project was created because of this tRPC issue opened by the creator of tRPC.

Note

Make sure to use the next version of tRPC. Meaning when installing a tRPC related package, make sure to install the @next version.

pnpm install @trpc/server@next @trpc/client@next ...
import {
  createTRPCStoreLimiter,
  defaultFingerPrint,
} from '@trpc-limiter/memory'

// or

import {
  createTRPCUpstashLimiter,
  defaultFingerPrint,
} from '@trpc-limiter/upstash'

// or

import { createTrpcRedisLimiter, defaultFingerPrint } from '@trpc-limiter/redis'

Example (Redis)

import { initTRPC } from '@trpc/server'
import { type NextApiRequest } from 'next'
import { createTrpcRedisLimiter, defaultFingerPrint } from '@trpc-limiter/redis'
import { createClient } from 'redis'

export const redis = createClient({
  password: '...',
  socket: {
    host: '...',
    port: 18382,
  },
  disableOfflineQueue: true,
})

type Context = {
  req: NextApiRequest
}

const t = initTRPC.context<Context>().create()

const rateLimiter = createTrpcRedisLimiter<typeof t>({
  fingerprint: (ctx) => defaultFingerPrint(ctx.req),
  message: (hitInfo) => `Too many requests, please try again later. ${hitInfo}`,
  max: 15,
  windowMs: 10000,
  redisClient: redis,
})

export const rateLimitedProcedure = t.procedure.use(rateLimiter)