# @geekmidas/rate-limit 中文文档

规范地址：https://npmcn.com/package/%40geekmidas/rate-limit/

版本：9\.6\.1
npm 元数据更新时间：2026-11-16T09:31:59.288Z
中文译文更新时间：2026-11-16T09:37:17.410Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40geekmidas/rate-limit
原文对照：https://npmcn.com/package/%40geekmidas/rate-limit/?lang=original
项目主页：https://github.com/geekmidas/toolbox#readme
源码仓库：https://github.com/geekmidas/toolbox

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：70.7 kB，15 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- peer 依赖：@geekmidas/cache ^9\.6\.1，@geekmidas/logger ^9\.6\.1，@geekmidas/services ^9\.6\.1
- 首次发布：2025-10-19T18:21:52.252Z
- 最新版本发布：2026-11-16T09:31:58.626Z
- 近 30 天下载量：13341（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：203（近 12 个月 202 个）

## 中文简介

灵活速率限制库,支持多个缓存后端,自定义密钥生成,以及完整的TypeScript支持.

## 安装

```sh
npm install @geekmidas/rate-limit
```

也可以使用：`pnpm add @geekmidas/rate-limit`、`yarn add @geekmidas/rate-limit`、`bun add @geekmidas/rate-limit`

## README

# @geekmidas/ 速率限制

灵活速率限制库,支持多个缓存后端,自定义密钥生成,以及完整的TypeScript支持.

## 特征

-   **多个缓存后端**: 任何缓存执行的工程( Redis, In- Memory等)
-   **灵活密钥生成**: 自定义客户端识别方式
-   **跳过逻辑**: 有条件地跳过某些请求的速率限制
-   **标准信头**: 自动速率限制头生成
-   **类型安全**: 全类型脚本支持和通用类型
-   **可自定义**: 配置限制、窗口、信件和处理器
-   **IP 检测**: 从各种信头自动检测客户端 IP

## 安装

```bash
pnpm add @geekmidas/rate-limit
```

## 快速启动

### 基本用途

```typescript
import { checkRateLimit } from '@geekmidas/rate-limit';
import { InMemoryCache } from '@geekmidas/cache/memory';

const config = {
  limit: 10,                           // 10 requests
  windowMs: 60000,                     // per 1 minute
  cache: new InMemoryCache(),          // storage backend
};

// In your handler
try {
  const info = await checkRateLimit(config, {
    header: (key) => request.headers.get(key),
    services: {},
    logger,
    session: null,
    path: '/api/users',
    method: 'GET'
  });

  // Request allowed
  console.log(`${info.remaining} requests remaining`);
} catch (error) {
  if (error instanceof TooManyRequestsError) {
    // Rate limit exceeded
    console.log(`Try again in ${error.retryAfter} seconds`);
  }
}
```

### 有终点

速率限制包含在构造包中 :

```typescript
import { e } from '@geekmidas/constructs/endpoints';
import { InMemoryCache } from '@geekmidas/cache/memory';
import { z } from 'zod';

export const sendMessage = e
  .post('/api/messages')
  .rateLimit({
    limit: 10,                    // 10 requests
    windowMs: 60000,             // per minute
    cache: new InMemoryCache(),
    message: 'Too many messages sent. Please try again later.'
  })
  .body(z.object({
    content: z.string()
  }))
  .handle(async ({ body }) => {
    // Rate limited to 10 requests per minute
    return { success: true };
  });
```

## 配置

### 速率限制配置

```typescript
interface RateLimitConfig {
  limit: number;           // Max requests in window
  windowMs: number;        // Time window in milliseconds
  cache: Cache;            // Cache backend
  keyGenerator?: RateLimitKeyGenerator; // Custom key generation
  skip?: RateLimitSkipFn;  // Skip certain requests
  message?: string;        // Custom error message
  handler?: RateLimitExceededHandler; // Custom exceeded handler
  standardHeaders?: boolean; // Include standard headers (default: true)
  legacyHeaders?: boolean;   // Include legacy headers (default: false)
}
```

## 缓存后端

### 记忆缓存

最佳发展和单项部署:

```typescript
import { InMemoryCache } from '@geekmidas/cache/memory';

const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache()
};
```

### Redis (上图)

最佳生产和分配系统:

```typescript
import { UpstashCache } from '@geekmidas/cache/upstash';

const config = {
  limit: 100,
  windowMs: 60000,
  cache: new UpstashCache({
    url: process.env.UPSTASH_REDIS_URL,
    token: process.env.UPSTASH_REDIS_TOKEN
  })
};
```

## 自定义密钥生成

### 根据用户代号

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  keyGenerator: (ctx) => {
    const userId = ctx.session?.userId || 'anonymous';
    return `rate-limit:${ctx.method}:${ctx.path}:${userId}`;
  }
};
```

### 根据 API 密钥

```typescript
const config = {
  limit: 1000,
  windowMs: 3600000, // 1 hour
  cache: new InMemoryCache(),
  keyGenerator: (ctx) => {
    const apiKey = ctx.header('x-api-key') || 'unknown';
    return `rate-limit:${ctx.path}:${apiKey}`;
  }
};
```

### 通过IP和用户代理

```typescript
const config = {
  limit: 50,
  windowMs: 60000,
  cache: new InMemoryCache(),
  keyGenerator: (ctx) => {
    const ip = ctx.header('x-forwarded-for')?.split(',')[0] || 'unknown';
    const userAgent = ctx.header('user-agent') || 'unknown';
    return `rate-limit:${ip}:${userAgent}`;
  }
};
```

## 跳过逻辑

### 跳过认证用户

```typescript
const config = {
  limit: 10,
  windowMs: 60000,
  cache: new InMemoryCache(),
  skip: (ctx) => {
    // Skip rate limiting for authenticated users
    return !!ctx.session?.userId;
  }
};
```

### 跳过管理路由

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  skip: (ctx) => {
    // Skip rate limiting for admin routes
    return ctx.path.startsWith('/admin/');
  }
};
```

### 跳过内部IP

```typescript
const config = {
  limit: 10,
  windowMs: 60000,
  cache: new InMemoryCache(),
  skip: (ctx) => {
    const ip = ctx.header('x-forwarded-for')?.split(',')[0];
    // Skip rate limiting for internal IPs
    return ip?.startsWith('10.') || ip?.startsWith('192.168.');
  }
};
```

## 自定义处理器

### 日志速率限制违反

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  handler: async (ctx, info) => {
    ctx.logger.warn({
      path: ctx.path,
      method: ctx.method,
      count: info.count,
      limit: info.limit,
      ip: ctx.header('x-forwarded-for')
    }, 'Rate limit exceeded');
  }
};
```

### 虐待警报

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  handler: async (ctx, info) => {
    // Alert if significantly over limit
    if (info.count > info.limit * 2) {
      await alertService.send({
        type: 'rate_limit_abuse',
        ip: ctx.header('x-forwarded-for'),
        count: info.count,
        path: ctx.path
      });
    }
  }
};
```

## 答复信头

库会自动设置标准费率限制头 :

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 2024-01-15T12:34:56.789Z
Retry-After: 45
```

### 禁用信头

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  standardHeaders: false  // Disable standard headers
};
```

### 启用遗留信头

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  legacyHeaders: true  // Enable legacy headers
};
```

## 费率限制信息

这个 `checkRateLimit` 函数返回当前速率限制状态的信息 :

```typescript
interface RateLimitInfo {
  count: number;        // Current request count
  limit: number;        // Max allowed requests
  remaining: number;    // Remaining requests
  resetTime: number;    // Unix timestamp when window resets
  retryAfter: number;   // Milliseconds until reset
}

const info = await checkRateLimit(config, ctx);
console.log(`You have ${info.remaining} requests remaining`);
console.log(`Rate limit resets at ${new Date(info.resetTime)}`);
```

## 处理错误

### 太多请求错误

超过利率限制时抛出 :

```typescript
import { TooManyRequestsError } from '@geekmidas/rate-limit';

try {
  await checkRateLimit(config, ctx);
} catch (error) {
  if (error instanceof TooManyRequestsError) {
    console.log(`Status: ${error.statusCode}`); // 429
    console.log(`Message: ${error.message}`);
    console.log(`Retry after: ${error.retryAfter} seconds`);

    // Send appropriate response
    return new Response(error.message, {
      status: error.statusCode,
      headers: {
        'Retry-After': error.retryAfter?.toString() || '60'
      }
    });
  }
}
```

## 常见模式

### 不同终点的不同限制

```typescript
// Strict limit for auth endpoints
export const login = e
  .post('/auth/login')
  .rateLimit({
    limit: 5,
    windowMs: 300000, // 5 minutes
    cache: new InMemoryCache(),
    message: 'Too many login attempts. Please try again later.'
  })
  .handle(async () => {
    // Login logic
  });

// Generous limit for read endpoints
export const getUsers = e
  .get('/users')
  .rateLimit({
    limit: 1000,
    windowMs: 60000, // 1 minute
    cache: new InMemoryCache()
  })
  .handle(async () => {
    // Get users logic
  });
```

### 等级税率限制

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache: new InMemoryCache(),
  keyGenerator: (ctx) => {
    // Different limits based on user tier
    const tier = ctx.session?.tier || 'free';
    const limit = tier === 'premium' ? 1000 : 100;

    return `rate-limit:${tier}:${ctx.path}:${ctx.session?.userId}`;
  }
};
```

### API 键限制

```typescript
const config = {
  limit: 10000,
  windowMs: 3600000, // 1 hour
  cache: new UpstashCache({ /* config */ }),
  keyGenerator: (ctx) => {
    const apiKey = ctx.header('x-api-key');
    if (!apiKey) {
      throw new Error('API key required');
    }
    return `rate-limit:api-key:${apiKey}`;
  },
  message: 'API rate limit exceeded. Upgrade your plan for higher limits.'
};
```

## 测试

锁定缓存进行测试 :

```typescript
import { checkRateLimit, type RateLimitData } from '@geekmidas/rate-limit';
import { vi } from 'vitest';

const mockCache = {
  get: vi.fn(),
  set: vi.fn(),
  delete: vi.fn()
};

const config = {
  limit: 10,
  windowMs: 60000,
  cache: mockCache as any
};

// Test rate limit not exceeded
mockCache.get.mockResolvedValue({ count: 5, resetTime: Date.now() + 30000 });

const info = await checkRateLimit(config, ctx);
expect(info.remaining).toBe(5);

// Test rate limit exceeded
mockCache.get.mockResolvedValue({ count: 11, resetTime: Date.now() + 30000 });

await expect(checkRateLimit(config, ctx)).rejects.toThrow(TooManyRequestsError);
```

## 最佳做法

### 1\. 在生产中使用Redis

```typescript
// ✅ Use Redis for distributed systems
import { UpstashCache } from '@geekmidas/cache/upstash';

const cache = new UpstashCache({ /* config */ });

// ❌ Don't use in-memory cache in production
const cache = new InMemoryCache(); // Only for dev/testing
```

### 2\. 设定适当限度

```typescript
// ✅ Different limits for different operations
const authConfig = { limit: 5, windowMs: 300000 }; // 5 per 5 min
const readConfig = { limit: 1000, windowMs: 60000 }; // 1000 per min

// ❌ Don't use same limit for everything
const config = { limit: 100, windowMs: 60000 }; // Too generic
```

### 3\. 包含帮助错误消息

```typescript
// ✅ Clear, actionable messages
message: 'Rate limit exceeded. You can make 100 requests per minute. Please try again in 45 seconds.'

// ❌ Generic messages
message: 'Too many requests'
```

### 4\. 日志率限制事件

```typescript
const config = {
  limit: 100,
  windowMs: 60000,
  cache,
  handler: async (ctx, info) => {
    ctx.logger.warn({
      event: 'rate_limit_exceeded',
      path: ctx.path,
      count: info.count,
      limit: info.limit
    }, 'Rate limit exceeded');
  }
};
```

## 相关软件包

-   [@ geekmidas/ cache (笑声)](https://npmcn.com/package/%40geekmidas/cache) - 限制费率的缓存执行
-   [@geekmidas/ 构造](https://npmcn.com/package/%40geekmidas/constructs) - 限制终点的内置费率
-   [@geekmidas/错误](https://npmcn.com/package/%40geekmidas/errors) - HTTP 错误分类
-   [@ geekmidas/ logger (英语)](https://npmcn.com/package/%40geekmidas/logger) - 结构化伐木

## 许可证

麻省理工学院

## 常见问题

### @geekmidas/rate-limit 是什么？

灵活速率限制库,支持多个缓存后端,自定义密钥生成,以及完整的TypeScript支持\.

### 如何安装 @geekmidas/rate-limit？

在项目目录运行 npm install @geekmidas/rate-limit，或使用 pnpm add / yarn add / bun add。

### @geekmidas/rate-limit 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @geekmidas/rate-limit 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @geekmidas/rate-limit 可以商用吗？

@geekmidas/rate-limit 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @geekmidas/rate-limit 的下载量有多少？

根据 npm 官方下载统计，@geekmidas/rate-limit 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,341 次，日均约 445 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @geekmidas/rate-limit 还在维护吗？

最新版本 9\.6\.1 发布于 2026/11/16（今天）；至今共发布 203 个版本，其中过去 12 个月发布了 202 个；首次发布于 2025/10/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

