0
0
Expressframework~5 mins

In-memory caching with node-cache in Express

Choose your learning style9 modes available
Introduction

In-memory caching stores data temporarily in your app's memory. It helps your app respond faster by reusing data instead of fetching it again.

You want to speed up repeated requests for the same data.
You want to reduce calls to a slow database or external API.
You want to store small data temporarily during app runtime.
You want to improve user experience by reducing wait times.
You want to limit resource use by avoiding repeated heavy calculations.
Syntax
Express
import NodeCache from 'node-cache';

const cache = new NodeCache({ stdTTL: 100, checkperiod: 120 });

// Set a value
cache.set(key, value, ttlInSeconds);

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

// Delete a value
cache.del(key);

stdTTL sets default time to live (seconds) for cached items.

checkperiod is how often expired items are cleaned up.

Examples
Stores user data with key 'user_1' for 5 minutes.
Express
cache.set('user_1', { name: 'Alice' }, 300);
Retrieves cached user data and checks if it exists.
Express
const user = cache.get('user_1');
if (user) {
  console.log('User found:', user.name);
} else {
  console.log('User not in cache');
}
Removes the cached data for 'user_1'.
Express
cache.del('user_1');
Sample Program

This Express app uses node-cache to store data for 60 seconds. When you request '/data', it first checks the cache. If data is there, it returns cached data quickly. If not, it creates fresh data, caches it, and returns it.

Express
import express from 'express';
import NodeCache from 'node-cache';

const app = express();
const cache = new NodeCache({ stdTTL: 60 }); // cache items live 60 seconds

app.get('/data', (req, res) => {
  const key = 'myData';
  const cachedData = cache.get(key);

  if (cachedData) {
    return res.send({ source: 'cache', data: cachedData });
  }

  // Simulate slow data fetch
  const freshData = { message: 'Hello from server', time: new Date().toISOString() };

  cache.set(key, freshData);
  res.send({ source: 'server', data: freshData });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Cache is stored in app memory, so it resets if the app restarts.

Use caching only for data that can be temporarily stored and safely reused.

Be mindful of cache size and expiration to avoid memory issues.

Summary

In-memory caching speeds up your app by storing data temporarily.

node-cache is a simple tool to add caching in Node.js apps.

Always check cache before fetching fresh data to save time.