JAVASCRIPT
Implement Server-Side Caching for External API Responses
Improve API performance and reduce external service load by implementing server-side caching for frequently accessed data using Node.js and a simple cache library.
const express = require('express');
const NodeCache = require('node-cache');
const fetch = require('node-fetch'); // Use 'cross-fetch' or similar for isomorphic fetch if needed
const app = express();
const myCache = new NodeCache({ stdTTL: 300, checkperiod: 120 }); // Cache for 5 minutes
const EXTERNAL_API_URL = 'https://api.example.com/data';
app.get('/cached-data', async (req, res) => {
const cacheKey = 'external_data';
let data = myCache.get(cacheKey);
if (data) {
console.log('Serving from cache!');
return res.json(data);
}
console.log('Fetching from external API...');
try {
const response = await fetch(EXTERNAL_API_URL);
if (!response.ok) {
throw new Error(`API error: ${response.statusText}`);
}
data = await response.json();
myCache.set(cacheKey, data);
res.json(data);
} catch (error) {
console.error('Failed to fetch data:', error);
res.status(500).json({ error: 'Failed to retrieve data' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to implement server-side caching for external API responses. It uses the `node-cache` library to store data fetched from `EXTERNAL_API_URL`. When a request comes to `/cached-data`, it first checks if the data exists in the cache. If found, it serves the cached data immediately. If not, it fetches the data from the external API, stores it in the cache for a specified duration (`stdTTL`), and then sends it to the client. This significantly reduces the load on the external API and improves response times for subsequent requests.