typescript 60 lines · 7 steps

A rate-limiting guard in NestJS

A custom guard reads per-route metadata and tracks request counts in memory to throttle callers.

Explained by highlit
1import {
2 CanActivate,
3 ExecutionContext,
4 Injectable,
5 HttpException,
6 HttpStatus,
7} from '@nestjs/common';
8import { Reflector } from '@nestjs/core';
9import { Request } from 'express';
10 
11export const RATE_LIMIT_KEY = 'rate_limit';
12 
13export interface RateLimitOptions {
14 limit: number;
15 windowMs: number;
16}
17 
18export const RateLimit = (options: RateLimitOptions) =>
19 Reflect.metadata(RATE_LIMIT_KEY, options);
20 
21interface Bucket {
22 count: number;
23 expiresAt: number;
24}
25 
26@Injectable()
27export class RateLimitGuard implements CanActivate {
28 private readonly store = new Map<string, Bucket>();
29 
30 constructor(private readonly reflector: Reflector) {}
31 
32 canActivate(context: ExecutionContext): boolean {
33 const options = this.reflector.getAllAndOverride<RateLimitOptions>(
34 RATE_LIMIT_KEY,
35 [context.getHandler(), context.getClass()],
36 );
37 if (!options) return true;
38 
39 const request = context.switchToHttp().getRequest<Request>();
40 const key = `${request.ip}:${context.getHandler().name}`;
41 const now = Date.now();
42 const bucket = this.store.get(key);
43 
44 if (!bucket || bucket.expiresAt <= now) {
45 this.store.set(key, { count: 1, expiresAt: now + options.windowMs });
46 return true;
47 }
48 
49 if (bucket.count >= options.limit) {
50 const retryAfter = Math.ceil((bucket.expiresAt - now) / 1000);
51 throw new HttpException(
52 { statusCode: HttpStatus.TOO_MANY_REQUESTS, message: 'Rate limit exceeded', retryAfter },
53 HttpStatus.TOO_MANY_REQUESTS,
54 );
55 }
56 
57 bucket.count += 1;
58 return true;
59 }
60}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Guards can pair with a custom decorator so per-route config travels as metadata read via the Reflector.
  2. 2A fixed-window counter needs only a count and an expiry timestamp per key to enforce limits.
  3. 3Throwing HttpException from a guard lets you return rich responses like a 429 with retryAfter.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
python
import secrets
 
from django.contrib.auth import authenticate, login
from django.core.cache import cache

Two-factor login with OTP in Django

two-factor-auth one-time-passwords caching
Intermediate 9 steps

Share this explainer

Here's the card — post it anywhere.

A rate-limiting guard in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code