API Developmentintermediate
Add caching layer to API responses
API Caching
Add caching layer to API responses
Add caching layer to API responses.
Instructions
- HTTP caching headers:
export async function GET(req: Request) {
const data = await fetchData();
const etag = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
// Check if client has current version
if (req.headers.get('if-none-match') === etag) {
return new Response(null, { status: 304 });
}
return Response.json({ data }, {
headers: {
'Cache-Control': 'public, max-age=60, stale-while-revalidate=300',
'ETag': etag,
},
});
}
- Server-side caching with Redis:
async function getCachedOrFetch<T>(key: string, ttlSeconds: number, fetcher: () => Promise<T>): Promise<T> {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const data = await fetcher();
await redis.setex(key, ttlSeconds, JSON.stringify(data));
return data;
}
// Usage
const users = await getCachedOrFetch('users:list', 60, () => db.user.findMany());
Cache Invalidation
- Invalidate on write: after POST/PATCH/DELETE, delete related cache keys
- Use cache tags to invalidate groups:
users:* - Set reasonable TTLs: 60s for lists, 300s for rarely-changed data