diff --git a/examples/next/src/server/trpc/trpc.ts b/examples/next/src/server/trpc/trpc.ts index 0877b5d..70b5548 100644 --- a/examples/next/src/server/trpc/trpc.ts +++ b/examples/next/src/server/trpc/trpc.ts @@ -11,13 +11,17 @@ const root = initTRPC.context().create({ }, }); -const getFingerPrint = (req: NextApiRequest) => { - const ip = req.socket.remoteAddress ?? req.headers["x-forwarded-for"]; - return (Array.isArray(ip) ? ip[0] : ip) ?? "127.0.0.1"; -}; +const getFingerprint = (req: NextApiRequest) => { + const forwarded = req.headers["x-forwarded-for"] + const ip = forwarded + ? (typeof forwarded === "string" ? forwarded : forwarded[0])?.split(/, /)[0] + : req.socket.remoteAddress + return ip || "127.0.0.1" +} + export const rateLimiter = createTRPCUpstashLimiter({ root, - fingerprint: (ctx) => getFingerPrint(ctx.req), + fingerprint: (ctx) => getFingerprint(ctx.req), windowMs: 20000, message: (hitInfo) => `Too many requests, please try again later. ${Math.ceil( diff --git a/packages/upstash/README.md b/packages/upstash/README.md index b7c5dae..176fa3f 100644 --- a/packages/upstash/README.md +++ b/packages/upstash/README.md @@ -30,13 +30,17 @@ type Context = { } const root = initTRPC.context().create() -const getFingerPrint = (req: NextApiRequest) => { - const ip = req.socket.remoteAddress ?? req.headers['x-forwarded-for'] - return (Array.isArray(ip) ? ip[0] : ip) ?? '127.0.0.1' +const getFingerprint = (req: NextApiRequest) => { + const forwarded = req.headers["x-forwarded-for"] + const ip = forwarded + ? (typeof forwarded === "string" ? forwarded : forwarded[0])?.split(/, /)[0] + : req.socket.remoteAddress + return ip || "127.0.0.1" } + export const rateLimiter = createTRPCUpstashLimiter({ root, - fingerprint: (ctx, _input) => getFingerPrint(ctx.req), + fingerprint: (ctx, _input) => getFingerprint(ctx.req), windowMs: 10000, message: (hitInfo) => `Too many requests, please try again later. ${Math.ceil(