Prompt

How do I cache API responses in a web app?

Technology / Cloud Infrastructure1 observationLast seen Oct 25, 2026

Latest observation

Oct 25, 2026OpenAI APIWeb search: off

Caching API responses in a web app usually means storing previously fetched data so you can reuse it instead of calling the server every time. This can improve speed, reduce bandwidth, and lower load on your backend.

Common places to cache

1. Browser/client-side cache

Good for:

  • Repeated reads
  • Improving perceived performance
  • Offline support

Options:

  • HTTP caching headers set by your API
  • In-memory cache in your app
  • localStorage / sessionStorage for small, simple data
  • IndexedDB for larger or structured data
  • Service Worker Cache API for offline/network control

2. Server-side cache

Good for:

  • Reusing expensive API responses
  • Protecting databases
  • Shared cache across users

Options:

  • Redis
  • Memcached
  • App-level in-memory cache
  • CDN edge caching for public GET endpoints

Best practice: use HTTP caching first

If your API is under your control, configure cache headers so browsers and CDNs can cache responses.

Example headers:

Cache-Control: public, max-age=60, stale-while-revalidate=300
ETag: "abc123"
Last-Modified: Tue, 14 Oct 2025 12:00:00 GMT

What they do

  • Cache-Control: max-age=60 → cache for 60 seconds
  • stale-while-revalidate=300 → serve stale data while fetching fresh data in background
  • ETag / Last-Modified → enable conditional requests so the server can reply 304 Not Modified

Simple client-side cache example

In-memory cache

const cache = new Map();

async function fetchWithCache(url) {
  if (cache.has(url)) {
    return cache.get(url);
  }

  const response = await fetch(url);
  const data = await response.json();
  cache.set(url, data);
  return data;
}

This is fast, but the cache disappears when the page reloads.


Cache with expiration

const cache = new Map();
const TTL = 60 * 1000; // 60 seconds

async function fetchWithCache(url) {
  const cached = cache.get(url);

  if (cached && Date.now() < cached.expiresAt) {
    return cached.data;
  }

  const response = await fetch(url);
  const data = await response.json();

  cache.set(url, {
    data,
    expiresAt: Date.now() + TTL
  });

  return data;
}

Use localStorage for small persisted cache

async function fetchWithLocalStorageCache(url) {
  const key = `cache:${url}`;
  const cached = JSON.parse(localStorage.getItem(key) || "null");

  if (cached && Date.now() < cached.expiresAt) {
    return cached.data;
  }

  const response = await fetch(url);
  const data = await response.json();

  localStorage.setItem(key, JSON.stringify({
    data,
    expiresAt: Date.now() + 60 * 1000
  }));

  return data;
}

Note: localStorage is synchronous and not ideal for large data or frequent access.


Use a data-fetching library

In modern web apps, libraries like:

  • React Query
  • SWR
  • RTK Query

handle caching, deduping, revalidation, retries, and stale data automatically.

Example with SWR:

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then(res => res.json());

function Profile() {
  const { data, error, isLoading } = useSWR('/api/profile', fetcher, {
    revalidateOnFocus: true,
    dedupingInterval: 5000
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error</div>;

  return <div>{data.name}</div>;
}

Important caching rules

Don’t cache everything

Avoid caching:

  • User-specific sensitive data unless properly scoped
  • Frequently changing data without invalidation
  • POST/PUT/DELETE responses unless you know what you’re doing

Use cache keys carefully

Include things like:

  • URL
  • Query parameters
  • User ID or auth context if data is user-specific
  • Locale or feature flags if relevant

Invalidate when data changes

If the user updates data, clear or refresh related cache entries.


A good strategy

  1. Set proper HTTP cache headers on API responses
  2. Use a client-side caching library in the frontend
  3. Add server-side cache for expensive endpoints
  4. Define invalidation rules carefully

If you want, I can also show:

  • how to do this in React
  • how to implement Redis caching on the backend
  • how to use ETag/304 responses for efficient caching

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.