Node.js8 min read
Caching with Redis in Node.js
Speed up your Node.js app with Redis caching. Learn key-value storage, expiration, and caching strategies.
Sarah Chen
December 19, 2025
0.0k0
Caching with Redis in Node.js
Redis is an in-memory data store. Perfect for caching, sessions, and real-time data.
Setup
npm install redis
# Make sure Redis server is running
Connect to Redis
const redis = require('redis');
const client = redis.createClient({
url: 'redis://localhost:6379'
});
client.on('error', err => console.log('Redis Error:', err));
await client.connect();
console.log('Connected to Redis');
Basic Operations
// Set and get
await client.set('name', 'Alice');
const name = await client.get('name'); // 'Alice'
// Set with expiration (seconds)
await client.setEx('session', 3600, 'data'); // Expires in 1 hour
// Delete
await client.del('name');
// Check if exists
const exists = await client.exists('name'); // 0 or 1
Working with JSON
// Store object as JSON
const user = { id: 1, name: 'Alice' };
await client.set('user:1', JSON.stringify(user));
// Retrieve and parse
const data = await client.get('user:1');
const parsed = JSON.parse(data);
Hash (Objects)
// Set hash fields
await client.hSet('user:1', {
name: 'Alice',
email: 'alice@example.com',
age: '25'
});
// Get all fields
const user = await client.hGetAll('user:1');
// { name: 'Alice', email: 'alice@example.com', age: '25' }
// Get single field
const name = await client.hGet('user:1', 'name');
Caching Database Queries
async function getUser(id) {
const cacheKey = `user:${id}`;
// Check cache first
const cached = await client.get(cacheKey);
if (cached) {
console.log('Cache hit');
return JSON.parse(cached);
}
// Cache miss - fetch from database
console.log('Cache miss');
const user = await User.findById(id);
if (user) {
// Cache for 1 hour
await client.setEx(cacheKey, 3600, JSON.stringify(user));
}
return user;
}
Cache Middleware
function cache(duration) {
return async (req, res, next) => {
const key = `cache:${req.originalUrl}`;
const cached = await client.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
// Store original res.json
const originalJson = res.json.bind(res);
res.json = async (data) => {
await client.setEx(key, duration, JSON.stringify(data));
return originalJson(data);
};
next();
};
}
// Usage
app.get('/api/posts', cache(300), async (req, res) => {
const posts = await Post.find();
res.json(posts);
});
Cache Invalidation
async function updateUser(id, data) {
// Update database
const user = await User.findByIdAndUpdate(id, data, { new: true });
// Invalidate cache
await client.del(`user:${id}`);
return user;
}
// Clear all user caches
async function clearUserCache() {
const keys = await client.keys('user:*');
if (keys.length) {
await client.del(keys);
}
}
Lists & Sets
// List - ordered
await client.lPush('queue', 'task1');
await client.lPush('queue', 'task2');
const task = await client.rPop('queue'); // 'task1'
// Set - unique values
await client.sAdd('tags', 'nodejs');
await client.sAdd('tags', 'redis');
const tags = await client.sMembers('tags'); // ['nodejs', 'redis']
Session Storage
const session = require('express-session');
const RedisStore = require('connect-redis').default;
app.use(session({
store: new RedisStore({ client }),
secret: 'your-secret',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 86400000 } // 1 day
}));
Key Takeaway
Redis dramatically speeds up reads by caching data in memory. Cache database queries, API responses, and sessions. Always set expiration times and invalidate cache when data changes. It's essential for high-performance Node.js apps.
#Node.js#Redis#Caching#Performance#Intermediate