Caching in TypeScript: Speed Up Your App Without Pain

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Your Application Is Slow (And How to Fix It)



Have you ever waited for the interface to redraw after a click? Or watched the server respond to the same request multiple times in a row? Sound familiar? Then this article is for you. Data caching is not just a "good practice," but a fundamental skill for any TypeScript developer who wants their application to fly, not crawl.



Today we'll break down how to properly cache data in TypeScript: from a simple in-memory cache on the frontend to advanced strategies with TTL and Redis on the backend. You'll get ready-to-use code snippets that you can drop into your project today.



What Is Caching and Why Do You Need It in TypeScript?



Caching is a technique for temporarily storing frequently used data in fast storage. Instead of fetching data from a database or remote server every time, we save the result of the first request and serve it on subsequent calls.



The benefits are obvious:

  • Reduced response time (latency) — users get data in milliseconds
  • Decreased load on the server and database
  • Saved bandwidth and resources
  • Ability to work offline (for frontend)


In TypeScript, thanks to its type system, we can write safe and predictable caching that won't break at runtime. Let's see how to do it.



Caching Strategies: Choosing the Right Approach



Before writing code, you need to understand which strategy you'll use. This determines how effective your solution will be.



1. In-Memory Cache

The simplest and fastest option. Data is stored in a variable, Map, or object. Ideal for frontend and small Node.js applications.

Drawback: data is lost on page reload or server restart.



2. LocalStorage / SessionStorage (Browser Cache)

Suitable for frontend when you need to persist data between sessions. Ideal for user settings, tokens, and caching API responses.

Drawback: synchronous access, size limit (5-10MB).



3. Redis (Server-Side Cache)

The industry standard for backend. Fast, reliable, with TTL support and complex data structures. Works great with Node.js via the ioredis library.

Drawback: requires a separate service (Redis server).



4. Service Worker + Cache API (PWA)

Advanced cache for Progressive Web Apps. Allows intercepting network requests and serving cached responses. Ideal for offline mode.



Writing a Cache in TypeScript: From Simple to Advanced



Now let's get practical. I'll show several implementations, from basic to advanced, using TypeScript generics.



Simple In-Memory Cache with TTL



Let's start with a classic — an in-memory cache with automatic removal of expired entries.



// cache.tsinterface CacheEntry<T> {    data: T;    expiry: number; // timestamp in milliseconds}

class SimpleCache<T> { private store = new Map<string, CacheEntry<T>>();

constructor(private defaultTTL: number = 60000) {} // 60 seconds by default

set(key: string, data: T, ttl?: number): void { const expiry = Date.now() + (ttl ?? this.defaultTTL); this.store.set(key, { data, expiry }); }

get(key: string): T | undefined { const entry = this.store.get(key); if (!entry) return undefined; if (Date.now() > entry.expiry) { this.store.delete(key); return undefined; // expired } return entry.data; }

has(key: string): boolean { return this.get(key) !== undefined; }

clear(): void {

Blogs

Book Recommendations