코딩일상
[npm] express-rate-limit: API 요청 제한 미들웨어 라이브러리 본문
express-rate-limit
기능정의
Express용 기본 속도 제한 미들웨어.
반복되는 요청을 암호 재설정과
같은 공용 API 및/또는 엔드포인트로 제한하는 데 사용합니다.
middleWare로 적용한 예제
1)
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})
2)
exports.apiLimiter = new RateLimit({
windowMs: 60 * 1000, // 1분 간격
max: 5, // windowMs동안 최대 호출 횟수
handler(req, res) { // 제한 초과 시 콜백 함수
res.status(this.statusCode).json({
code: this.statusCode, // statusCode 기본값은 429
message: '1분에 5번만 요청 할 수 있습니다.',
});
},
});
출처: https://inpa.tistory.com/entry/NODE-📚-API-사용량-제한하기 [Inpa Dev 👨💻:티스토리]
1)
app.post('/reset_password', limiter, (req, res) => {
// ...
})
옵션 설명
Option | FieldType | desc |
windowMs | number | 요청을 기억하는 시간(밀리초 단위). |
limit | number | function | 허용되는 요청의 최대 수. |
message | string | json | function | 제한에 도달한 후 반환할 응답. |
statusCode | number | 제한에 도달한 후 반환할 HTTP 상태 코드 (기본값은 429). |
legacyHeaders | boolean | X-Rate-Limit 헤더를 활성화합니다. |
standardHeaders | 'draft-6' | 'draft-7' | Ratelimit 헤더를 활성화합니다. |
requestPropertyName | string | req 객체에 비율 제한 정보를 추가합니다. |
skipFailedRequests | boolean | 4xx/5xx 응답을 카운트에서 제외합니다. |
skipSuccessfulRequests | boolean | 1xx/2xx/3xx 응답을 카운트에서 제외합니다. |
keyGenerator | function | 사용자를 식별하는 키를 생성합니다 (기본값은 IP 주소). |
handler | function | 제한에 도달한 후 실행할 함수 (message 및 statusCode 설정을 재정의할 수 있음). |
skip | function | 주어진 요청에 대해 리미터를 우회하도록 true를 반환합니다. |
requestWasSuccessful | function | skipFailedRequests 및 skipSuccessfulRequests에 사용됩니다. |
validate | boolean | object | 내장 검증 체크를 활성화하거나 비활성화합니다. |
store | Store | 여러 노드 간에 히트 수를 공유하는 데 사용되는 사용자 정의 저장소. |
* 더 자세한 내용은 아래 링크 참고를 하면 좋을 듯하다
Overview - express-rate-limit
The default MemoryStore stores the hit counts for clients in memory, and thus produces inconsistent results when running multiple servers or processes.
express-rate-limit.mintlify.app
참고
Usage - express-rate-limit
If your server runs behind a proxy/load balancer, the IP address of the request might be undefined, or the IP of the load balancer/reverse proxy (leading to the rate limiter blocking all requests once the limit is reached). To fix this, take a look at the
express-rate-limit.mintlify.app
[NODE] 📚 express-rate-limit 모듈 - API 사용량 제한하기
API 사용량 제한하기 만일 인증된 사용자가 과도한 API 사용을 하게 되면 API 서버에 무리가 갈 수 있다. 또한 DOS공격에도 대비해야 되는데, DOS란 지속적으로 서버에 요청을 과도하게 해서 서버를
inpa.tistory.com
'개발 공부 > Node.js' 카테고리의 다른 글
[Node.js] health-Check 헬스 체크 구현 (0) | 2024.05.17 |
---|---|
[Node.js] 메모리 누수 총 정리(1) (0) | 2024.03.12 |
[Node.js] node profiling 하기 (0) | 2024.03.04 |
서버 부하 테스트 Artillery (0) | 2022.10.03 |
Sequelize 알고 쓰자 장단점 (0) | 2022.09.16 |