typescript
44 lines · 7 steps
A tenant-aware HTTP cache in NestJS
Subclassing CacheInterceptor to key responses per tenant and read TTL from route metadata.
Explained by
highlit
1import {
2 CACHE_MANAGER,
3 CacheInterceptor,
4} from '@nestjs/cache-manager';
5import {
6 ExecutionContext,
7 Inject,
8 Injectable,
9} from '@nestjs/common';
10import { Reflector } from '@nestjs/core';
11import { Cache } from 'cache-manager';
12import { Request } from 'express';
13
14import { CACHE_TTL_METADATA } from './cache-ttl.decorator';
15
16@Injectable()
17export class HttpCacheInterceptor extends CacheInterceptor {
18 constructor(
19 @Inject(CACHE_MANAGER) cacheManager: Cache,
20 protected readonly reflector: Reflector,
21 ) {
22 super(cacheManager, reflector);
23 }
24
25 protected trackBy(context: ExecutionContext): string | undefined {
26 const request = context.switchToHttp().getRequest<Request>();
27
28 if (request.method !== 'GET') {
29 return undefined;
30 }
31
32 const tenant = request.headers['x-tenant-id'] ?? 'public';
33 return `${tenant}:${request.originalUrl}`;
34 }
35
36 protected getTtl(context: ExecutionContext): number | undefined {
37 const handlerTtl = this.reflector.getAllAndOverride<number>(
38 CACHE_TTL_METADATA,
39 [context.getHandler(), context.getClass()],
40 );
41
42 return handlerTtl ?? 30_000;
43 }
44}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Overriding trackBy lets you control exactly what counts as a unique cache key.
- 2Returning undefined from a cache key is the idiomatic way to opt a request out of caching.
- 3Reflector with getAllAndOverride reads per-handler metadata so config lives next to the route.
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
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 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
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-tenant-aware-http-cache-in-nestjs-explained-typescript-5725/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.