JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
junior
caching

What are the different types of caching for web applications?

caching
http-cache
localstorage
cdn
service-worker
Quick Answer

Web caching includes browser cache (HTTP headers like Cache-Control), CDN caching for static assets, application cache (localStorage, sessionStorage, IndexedDB), and service worker caching for offline support. Each serves different purposes.

Detailed Explanation

Types of Caching:

  1. Browser Cache (HTTP)

    • Cache-Control header
    • ETag for validation
    • Automatic, controlled by server
  2. CDN Cache

    • Edge servers worldwide
    • Reduces latency
    • Great for static assets
  3. Application Cache

    • localStorage: Persistent, 5-10MB
    • sessionStorage: Per-session
    • IndexedDB: Large data, structured
  4. Service Worker Cache

    • Programmable caching
    • Offline support
    • Custom strategies

Code Examples

HTTP caching headers
// Express.js cache headers
app.use('/static', express.static('public', {
  maxAge: '1y', // Cache static assets for 1 year
  immutable: true,
}));

// Different caching for different content
app.get('/api/data', (req, res) => {
  // No caching for API responses
  res.set('Cache-Control', 'no-store');
  res.json(data);
});

app.get('/api/config', (req, res) => {
  // Cache for 1 hour, allow stale while revalidating
  res.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
  res.json(config);
});

// Common Cache-Control values:
// - no-store: Never cache
// - no-cache: Cache but revalidate
// - public, max-age=31536000: Cache for 1 year
// - private, max-age=3600: User-specific, 1 hour

Resources

Web.dev - HTTP caching

article

MDN - Cache-Control

docs

Related Questions

How do service workers improve performance and what caching strategies exist?

senior
caching

What is lazy loading and how do you implement it?

junior
loading
Previous
What is lazy loading and how do you implement it?
Next
What is minification and bundling, and why are they important?