JAVASCRIPT

Server-Side Caching for External API Responses

Learn how to implement server-side caching for external API responses in Node.js, reducing redundant requests and improving application performance.

const NodeCache = require('node-cache');
const axios = require('axios');

// Initialize cache with a 10-minute (600 seconds) TTL
const apiCache = new NodeCache({ stdTTL: 600, checkperiod: 120 });

async function getCachedExternalData(url, cacheKey) {
    let data = apiCache.get(cacheKey);
    if (data) {
        console.log(`Cache hit for ${cacheKey}`);
        return data;
    }

    console.log(`Cache miss for ${cacheKey}, fetching data...`);
    try {
        const response = await axios.get(url);
        data = response.data;
        apiCache.set(cacheKey, data); // Cache the data
        console.log(`Data for ${cacheKey} cached.`);
        return data;
    } catch (error) {
        console.error(`Error fetching data from ${url}:`, error.message);
        throw error;
    }
}

// Example Usage (e.g., in an Express route)
/*
const express = require('express');
const app = express();

app.get('/api/posts', async (req, res) => {
    try {
        const posts = await getCachedExternalData('https://jsonplaceholder.typicode.com/posts', 'allPosts');
        res.json(posts);
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch posts' });
    }
});

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

// To test without Express:
(async () => {
    console.log('--- First call (should miss cache) ---');
    await getCachedExternalData('https://jsonplaceholder.typicode.com/todos/1', 'todo1');
    console.log('--- Second call (should hit cache) ---');
    await getCachedExternalData('https://jsonplaceholder.typicode.com/todos/1', 'todo1');
    // Wait for TTL to expire and check again (optional, for demo)
    // setTimeout(async () => {
    //     console.log('--- Call after TTL (should miss cache again) ---');
    //     await getCachedExternalData('https://jsonplaceholder.typicode.com/todos/1', 'todo1');
    // }, 610 * 1000);
})();
How it works: This snippet demonstrates server-side caching for external API responses using `node-cache` and `axios` in Node.js. The `getCachedExternalData` function first checks if data for a given `cacheKey` exists in the cache. If found, it returns the cached data immediately. Otherwise, it makes an actual API request, stores the response in the cache with a specified Time-To-Live (TTL), and then returns the data. This significantly reduces redundant calls to external APIs, improving performance and reducing external service load.

Need help integrating this into your project?

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

Hire DigitalCodeLabs