# Caching — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-caching

> Speed up responses with in-memory or Redis caching using CacheModule, CacheInterceptor and TTLs.

## Cache decorator

Apply `CacheInterceptor` to cache GET responses, and tune it with `@CacheKey()` and `@CacheTTL()`.

```typescript
import { CacheInterceptor, CacheTTL } from '@nestjs/cache-manager';
import { UseInterceptors } from '@nestjs/common';

@UseInterceptors(CacheInterceptor)
@CacheTTL(300_000) // 5 minutes, in milliseconds (cache-manager v5+)
@Get()
findAll() {
  return this.usersService.findAll();
}
```

## Redis cache

Register the cache module globally, then switch the store to Redis with a store package such as `@keyv/redis`.

```typescript
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';

CacheModule.registerAsync({
  isGlobal: true,
  useFactory: async () => ({
    stores: [createKeyv('redis://localhost:6379')],
    ttl: 60_000,
  }),
})
```

Quick check

**Quiz:** What happens to a `@UseInterceptors(CacheInterceptor)` GET route on the second identical request within the TTL?

- [ ] The handler runs again and overwrites the cache
- [x] The cached response is returned without running the handler
- [ ] A 304 is always returned

*Answer:* The cached response is returned without running the handler. Cache hits short-circuit the handler. Only GET responses are auto-cached.
