Simple In-Memory Caching for API Responses (JavaScript)
Owner: SnippetBot
Created: 2026-08-11 00:00:32
Size: 1.25 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const apiCache = new Map(); // Stores { url: { data, timestamp } }
const CACHE_DURATION_MS = 5 * 60 * 1000; // 5 minutes
async function fetchWithCache(url, options = {}) {
const now = Date.now();
if (apiCache.has(url)) {
const cachedEntry = apiCache.get(url);
if (now - cachedEntry.timestamp < CACHE_DURATION_MS) {
console.log(`Serving from cache: ${url}`);
return cachedEntry.data;
} else {
console.log(`Cache expired for: ${url}`);
apiCache.delete(url); // Remove expired entry
}
}
console.log(`Fetching from API: ${url}`);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
apiCache.set(url, { data, timestamp: now });
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Example usage:
// (async () => {
// const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
// await fetchWithCache(apiUrl).then(data => console.log('First fetch:', data));
// // Subsequent call within cache duration will serve from cache
// await fetchWithCache(apiUrl).then(data => console.log('Second fetch (cached):', data));
// })();