Skip to content

Open Source Rate Limiter Middleware For tRPC. Supporting Upstash, Memory Store And Much More

Notifications You must be signed in to change notification settings

OrJDev/trpc-limiter

Repository files navigation

tRPC Limiter

An open source, tRPC rate limiter middleware inspired by express-rate-limiter.

Install

npm install @trpc-limiter/core@latest

Usage

NextJS

import { initTRPC } from '@trpc/server'
import { createTRPCLimiter } from '@trpc-limiter/core'
import { type NextApiRequest } from 'next'

type Context = {
  req: NextApiRequest
  // ..etc
}

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

const getFingerPrint = (req: Context['req']) => {
  const ip = req.socket.remoteAddress ?? req.headers['x-forwarded-for']
  return (Array.isArray(ip) ? ip[0] : ip) ?? '127.0.0.1'
}

export const rateLimiter = createTRPCLimiter({
  root,
  fingerprint: (ctx) => getFingerPrint(ctx.req),
  windowMs: 10000,
  message: 'Too many requests, please try again later.',
  max: 15,
})

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

SolidStart

import { initTRPC } from '@trpc/server'
import { createTRPCLimiter } from '@trpc-limiter/core'

type Context = {
  req: Request
  // ..etc
}

export const root = initTRPC.context<Context>().create()

const limiter = createTRPCLimiter({
  root,
  fingerprint: (ctx) => ctx.req.headers.get('x-forwarded-for') ?? '127.0.0.1',
  windowMs: 20000,
  message: 'Too many requests, please try again later.',
  max: 15,
})

export const rateLimitedProcedure = root.procedure.use(limiter)

message

A message can be either a function that takes hitInfo, tRPC ctx and fingerprint or a string.

as a function

const opts = {
  message: (hitInfo, ctx, fingerprint) =>
    `Too many requests, please try again later. ${hitInfo.retryAfter}`,
}

as a string

const opts = {
  message: 'Too many requests, please try again later.',
}

onLimit

onLimit is a function that will be called when the request is blocked.

const opts = {
  onLimit: (hitInfo, ctx, fingerprint) => {
    console.log(hitInfo, ctx, fingerprint)
  },
}

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

About

Open Source Rate Limiter Middleware For tRPC. Supporting Upstash, Memory Store And Much More

Resources

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •