← Back to all snippets
JAVASCRIPT

Server-Side API Response Caching with Node.js and Redis

Boost performance and reduce external API calls in your Node.js application by implementing server-side response caching using Redis, managing data freshness effectively.

const express = require('express');
const axios = require('axios'); // For making external API calls
const redis = require('redis');

const app = express();
const PORT = process.env.PORT || 3000;
const REDIS_PORT = process.env.REDIS_PORT || 6379;
const EXTERNAL_API_URL = 'https://jsonplaceholder.typicode.com/posts'; // Example API

// Create Redis client
const redisClient = redis.createClient({
  port: REDIS_PORT,
  // host: 'your_redis_host' // Uncomment and set if Redis is not on localhost
});

redisClient.on('connect', () => console.log('Redis client connected'));
redisClient.on('error', err => console.error('Redis Client Error', err));

// Connect to Redis (async operation)
(async () => {
  await redisClient.connect();
})();

// Middleware to cache API responses
const cacheMiddleware = async (req, res, next) => {
  const cacheKey = req.originalUrl; // Use the request URL as the cache key
  
  try {
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log(`Cache hit for ${cacheKey}`);
      return res.send(JSON.parse(cachedData));
    }
    console.log(`Cache miss for ${cacheKey}`);
    // If not in cache, proceed to the route handler to fetch data
    next();
  } catch (err) {
    console.error('Redis cache error:', err);
    next(); // Continue without caching if Redis has issues
  }
};

// Route to fetch data from the external API with caching
app.get('/api/posts', cacheMiddleware, async (req, res) => {
  try {
    const { data } = await axios.get(EXTERNAL_API_URL);
    
    // Store data in Redis with an expiration time (e.g., 60 seconds)
    await redisClient.setEx(req.originalUrl, 60, JSON.stringify(data));
    
    res.send(data);
  } catch (error) {
    console.error('Error fetching from external API:', error.message);
    res.status(500).send('Failed to fetch data from external API');
  }
});

// Basic route for non-cached content
app.get('/', (req, res) => {
  res.send('Welcome to the API cache example!');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Open http://localhost:${PORT}/api/posts to test caching.`);
});
How it works: This Node.js snippet demonstrates how to implement server-side caching for external API responses using Redis. By caching frequently accessed data, you can significantly reduce the load on external services, improve response times, and potentially save costs. The `cacheMiddleware` intercepts requests, checks if the data is already in Redis, and serves it directly if found (cache hit). If not, it allows the request to proceed to the actual route handler, which fetches data from the external API, then stores it in Redis with a specified expiration time before sending it to the client. This 'cache-aside' pattern ensures that your application remains performant even when external dependencies are slow or rate-limited.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs