0
0
NodejsHow-ToBeginner · 4 min read

How to Use Caching in Node.js for Faster Performance

In Node.js, caching stores data temporarily to speed up repeated requests using in-memory objects or libraries like node-cache. You can cache results in variables or use packages to manage expiration and retrieval efficiently.
📐

Syntax

Basic caching in Node.js involves storing data in an object or using a caching library. Key parts include:

  • Cache store: Where data is saved (e.g., an object or library instance).
  • Set method: Saves data with a key.
  • Get method: Retrieves data by key.
  • TTL (time-to-live): Optional expiration time for cached data.
javascript
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 100 }); // TTL in seconds

// Set cache
cache.set('key', 'value');

// Get cache
const value = cache.get('key');
💻

Example

This example shows how to cache API results in memory using the node-cache package to avoid repeated slow calls.

javascript
import NodeCache from 'node-cache';
import fetch from 'node-fetch';

const cache = new NodeCache({ stdTTL: 60 }); // Cache expires in 60 seconds

async function getUserData(userId) {
  const cacheKey = `user_${userId}`;
  const cachedData = cache.get(cacheKey);
  if (cachedData) {
    return cachedData; // Return cached data if available
  }

  // Simulate API call
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
  const data = await response.json();

  cache.set(cacheKey, data); // Cache the data
  return data;
}

(async () => {
  console.log('Fetching user 1 first time...');
  console.log(await getUserData(1));

  console.log('Fetching user 1 second time (cached)...');
  console.log(await getUserData(1));
})();
Output
{ id: 1, name: 'Leanne Graham', username: 'Bret', ... } { id: 1, name: 'Leanne Graham', username: 'Bret', ... }
⚠️

Common Pitfalls

Common mistakes when using caching in Node.js include:

  • Not setting expiration (TTL), causing stale data.
  • Using global variables for cache in clustered apps, leading to inconsistent data.
  • Ignoring cache invalidation when data changes.
  • Storing large objects in memory causing high memory use.

Always plan cache size and expiration carefully.

javascript
import NodeCache from 'node-cache';
const cache = new NodeCache();

// Wrong: No TTL, cache never expires
cache.set('key', 'value');

// Right: Set TTL to expire cache
cache.set('key', 'value', 30); // expires in 30 seconds
📊

Quick Reference

Tips for caching in Node.js:

  • Use node-cache or similar libraries for easy TTL management.
  • Cache only data that is expensive to fetch or compute.
  • Always set expiration to avoid stale data.
  • Consider distributed caches like Redis for multi-instance apps.
  • Clear or update cache when underlying data changes.

Key Takeaways

Use in-memory caching with libraries like node-cache to speed up repeated data access.
Always set a TTL (time-to-live) to prevent stale cached data.
Avoid caching large data or use external caches like Redis for scalability.
Remember to invalidate or update cache when source data changes.
Test caching behavior to ensure it improves performance without causing bugs.