Caching in TypeScript: node-cache library

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

What is node-cache and why is it needed?

The node-cache library is a simple and fast caching system for Node.js, written in TypeScript. It allows you to store data in memory (in-memory cache), which significantly speeds up access to frequently requested information (e.g., database query results, API responses, computations). In TypeScript, node-cache provides strict typing, making the code more predictable and safe.

Caching is necessary to reduce server load, decrease response time, and save resources on repetitive operations. Node-cache is ideal for small and medium-sized projects where distributed caching (like Redis) is not required, but a lightweight in-memory cache is needed.

Installation

Install the package via npm or yarn:

npm install node-cache
# or
yarn add node-cache

For TypeScript, types are already included in the package; no need to install @types separately.

Main Functions

  • set(key, value, ttl) — saves a value by key with an optional time-to-live (TTL) in seconds.
  • get(key) — retrieves a value by key. Returns undefined if the key is missing or expired.
  • del(key) — deletes one or more keys.
  • has(key) — checks if a key exists in the cache.
  • flushAll() — clears the entire cache.
  • getStats() — returns statistics (number of keys, hits, misses).

Code Example in TypeScript

import NodeCache from 'node-cache';

// Create a cache instance with a default TTL of 60 seconds
const myCache = new NodeCache({ stdTTL: 60 });

// Typed value
interface User {
id: number;
name: string;
}

// Save data
const user: User = { id: 1, name: 'Alice' };
myCache.set('user_1', user);

// Retrieve data
const cachedUser = myCache.get<User>('user_1');
if (cachedUser) {
console.log(cachedUser.name); // Alice
} else {
console.log('Cache is empty');
}

// Check existence
console.log(myCache.has('user_1')); // true

// Deletion
myCache.del('user_1');

// Clear entire cache
myCache.flushAll();

When to Use node-cache

  • Frequently requested data: e.g., list of countries, currency rates, configurations.
  • Results of heavy computations: caching the result of an expensive operation for a few seconds.
  • API gateways: caching external API responses to reduce latency and limits.
  • Sessions: temporary storage of session data (if persistence is not required).

Avoid node-cache if you need distributed caching across multiple servers — in that case, it's better to use Redis. It is also not suitable for large volumes of data (more than 1-2 GB), as it is stored in RAM.

Node-cache is an excellent choice for simple caching scenarios in TypeScript where speed and minimal configuration are important.

Recommendations