Introduction
Caching helps store data temporarily to make apps faster and reduce work on servers.
Caching helps store data temporarily to make apps faster and reduce work on servers.
cache.set(key, value, { ttl: seconds })
cache.get(key)
cache.delete(key)cache.set saves data with a time limit (ttl).
cache.get retrieves saved data if it is still valid.
cache.set('user_123', {name: 'Anna'}, { ttl: 60 })
const user = cache.get('user_123')cache.delete('user_123')This example shows a simple cache using JavaScript Map. It stores user data for 30 seconds to avoid repeated database calls.
import { createClient } from '@supabase/supabase-js' const supabaseUrl = 'https://xyzcompany.supabase.co' const supabaseKey = 'public-anonymous-key' const supabase = createClient(supabaseUrl, supabaseKey) // Simple cache object const cache = new Map() // Function to set cache with TTL function cacheSet(key, value, ttl) { cache.set(key, { value, expires: Date.now() + ttl * 1000 }) } // Function to get cache function cacheGet(key) { const cached = cache.get(key) if (!cached) return null if (Date.now() > cached.expires) { cache.delete(key) return null } return cached.value } async function getUser(userId) { const cachedUser = cacheGet(userId) if (cachedUser) { console.log('Returning cached user') return cachedUser } const { data, error } = await supabase .from('users') .select('*') .eq('id', userId) .single() if (error) { console.error('Error fetching user:', error) return null } cacheSet(userId, data, 30) // Cache for 30 seconds console.log('Returning fresh user') return data } // Example usage (async () => { const user1 = await getUser('123') console.log(user1) const user2 = await getUser('123') console.log(user2) })()
Always set a time limit (TTL) to avoid stale data.
Clear cache when data changes to keep it fresh.
Use caching wisely to balance speed and accuracy.
Caching stores data temporarily to speed up apps.
Use TTL to control how long data stays in cache.
Check cache first before asking the database.
const cachedData = cache.get('user_123');
if (cachedData) {
console.log('Cache hit:', cachedData);
} else {
const data = await supabase.from('users').select('*').eq('id', 123);
cache.set('user_123', data, { ttl: 600 });
console.log('Cache miss, fetched:', data);
}const cached = cache.get('user_1');
if (!cached) {
const data = await supabase.from('users').select('*').eq('id', 1);
cache.set('user_1', data, { ttl: 300 });
}
console.log(cached);Pass the test and this pattern moves unknown