CLSkills
API Developmentintermediate

API Caching

Share

Add caching layer to API responses

API Caching

Add caching layer to API responses

Add caching layer to API responses.

Instructions

  1. 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,
    },
  });
}
  1. 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

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
apicachingperformance

Install command:

curl -o ~/.claude/skills/api-caching.md https://claude-skills-hub.vercel.app/skills/api/api-caching.md