Implementing Caching in Express.js
Caching stores frequently accessed data temporarily, so you don’t have to recompute or fetch it repeatedly. In Express, caching can be implemented at multiple levels:
Client-side caching (HTTP caching)
Server-side in-memory caching
Distributed caching (Redis, Memcached)
1. HTTP Client-Side Caching
Use HTTP headers to tell clients or proxies to cache responses.
Example: Using Cache-Control
const express = require('express');
const app = express();
app.get('/data', (req, res) => {
res.set('Cache-Control', 'public, max-age=60'); // cache for 60 seconds
res.json({ message: 'Hello, world!', timestamp: Date.now() });
});
app.listen(3000, () => console.log('Server running on port 3000'));
max-age: Time in seconds the client can cache the response.
public: Cacheable by any cache (client or proxy).
private: Cacheable only by the client.
no-cache / no-store: Prevent caching.
2. Server-Side In-Memory Caching
Useful for small apps or low-scale caching without external dependencies.
Using a simple object
const express = require('express');
const app = express();
const cache = {}; // simple in-memory cache
app.get('/time', (req, res) => {
if (cache['time']) {
return res.json({ source: 'cache', data: cache['time'] });
}
const data = { timestamp: Date.now() };
cache['time'] = data;
setTimeout(() => delete cache['time'], 60000); // invalidate after 60 sec
res.json({ source: 'server', data });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Fast for small datasets
Volatile (cleared when server restarts)
Not suitable for distributed setups
Using node-cache
npm install node-cache
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 60 }); // 60 seconds TTL
app.get('/users', (req, res) => {
const cachedData = cache.get('users');
if (cachedData) return res.json({ source: 'cache', data: cachedData });
// Simulate DB fetch
const users = [{ id: 1, name: 'Alice' }];
cache.set('users', users);
res.json({ source: 'server', data: users });
});
3. Distributed Caching with Redis
Redis is ideal for scalable caching across multiple server instances.
Setup Redis
npm install redis
const redis = require('redis');
const client = redis.createClient(); // defaults to localhost:6379
client.connect();
app.get('/products', async (req, res) => {
const cachedData = await client.get('products');
if (cachedData) return res.json({ source: 'cache', data: JSON.parse(cachedData) });
// Simulate DB fetch
const products = [{ id: 1, name: 'Laptop' }];
await client.setEx('products', 60, JSON.stringify(products)); // TTL 60 sec
res.json({ source: 'server', data: products });
});
Benefits of Redis:
Works in distributed environments
Supports TTL, eviction policies
Fast and reliable for high traffic
4. Route-Level Caching Middleware
You can create a reusable middleware for caching routes:
const cacheMiddleware = (duration) => async (req, res, next) => {
const key = req.originalUrl;
const cachedData = await client.get(key);
if (cachedData) return res.json(JSON.parse(cachedData));
res.sendResponse = res.json;
res.json = (body) => {
client.setEx(key, duration, JSON.stringify(body));
res.sendResponse(body);
};
next();
};
// Usage
app.get('/categories', cacheMiddleware(120), async (req, res) => {
const categories = [{ id: 1, name: 'Tech' }];
res.json(categories);
});
5. Best Practices
Choose the right caching layer:
Small apps → in-memory cache
Large/distributed apps → Redis or Memcached
Set proper TTL (time-to-live):
Critical data may need shorter TTL
Static data can have longer TTL
Cache only safe data:
Avoid caching sensitive or user-specific info without proper handling
Use cache invalidation:
Update or delete cache when underlying data changes
Monitor cache hit ratio:
Helps optimize caching strategy
Learn MERN Stack Training in Hyderabad
Read More
Building a Fraud Detection Pipeline with Spark MLlib on Dataproc
Running TensorFlow Distributed Training on Dataproc
Visit Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments