High-Performance Caching in Express.js With Redis

When building APIs or content-heavy applications, performance and response times are critical. By integrating Redis with Express.js, you can cache expensive operations like database queries and external API requests, dramatically improving your app's speed and scalability.

Why Use Redis for Caching?

  • In-memory storage for lightning-fast access
  • Supports TTL (time-to-live) expiration
  • Scales easily and is production-proven

Step 1: Set Up Express and Redis

npm init -y
npm install express ioredis
// server.js
const express = require('express');
const Redis = require('ioredis');
const app = express();
const redis = new Redis();

Step 2: Create a Middleware for Caching

async function cache(req, res, next) {
  const key = req.originalUrl;
  const cachedData = await redis.get(key);
  if (cachedData) {
    return res.send(JSON.parse(cachedData));
  }
  res.sendResponse = res.send;
  res.send = (body) => {
    redis.set(key, JSON.stringify(body), 'EX', 60); // cache for 60 seconds
    res.sendResponse(body);
  };
  next();
}

Step 3: Use It in Your Route

app.get('/api/data', cache, async (req, res) => {
  const data = await expensiveOperation(); // e.g., DB query
  res.send(data);
});

function expensiveOperation() {
  return new Promise(resolve => {
    setTimeout(() => resolve({ message: "Fresh data" }), 2000);
  });
}

app.listen(3000, () => console.log('Server running on port 3000'));

Benefits and Considerations

  • Improved response times for frequently accessed endpoints
  • Reduced load on backend services and databases
  • Be mindful of stale data; use TTLs or manual invalidation as needed

Conclusion

Adding Redis caching to an Express.js app is a simple but effective way to scale performance. Whether you’re building an API, dashboard, or SSR app, caching can make a big difference in both user experience and system efficiency.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift