0
0
ExpressHow-ToBeginner · 4 min read

How to Use Caching in Express for Faster Responses

To use caching in Express, you can set HTTP cache headers like Cache-Control on responses or use middleware such as apicache to store and serve cached data. This helps your app respond faster by reusing previous results instead of recalculating or refetching data.
📐

Syntax

In Express, caching is often done by setting HTTP headers or using middleware. The common pattern is:

  • res.set('Cache-Control', 'public, max-age=seconds') to tell browsers and proxies how long to cache.
  • Using middleware like apicache to automatically cache responses in memory.
javascript
app.get('/data', (req, res) => {
  res.set('Cache-Control', 'public, max-age=300'); // cache for 5 minutes
  res.send('Cached response');
});
💻

Example

This example shows how to use the apicache middleware to cache GET responses for 10 seconds. It speeds up repeated requests by returning cached data instead of running the handler again.

javascript
import express from 'express';
import apicache from 'apicache';

const app = express();
const cache = apicache.middleware;

app.get('/time', cache('10 seconds'), (req, res) => {
  res.json({ time: new Date().toISOString() });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When you visit http://localhost:3000/time multiple times within 10 seconds, // the time value stays the same because the response is cached.
⚠️

Common Pitfalls

Common mistakes when caching in Express include:

  • Setting cache headers too long for dynamic data, causing stale content.
  • Not clearing or invalidating cache when data changes.
  • Using caching middleware on POST or non-idempotent routes, which should not be cached.

Always choose appropriate cache duration and routes to cache.

javascript
/* Wrong: Caching POST request (should not cache) */
app.post('/submit', cache('5 minutes'), (req, res) => {
  res.send('Data saved');
});

/* Right: Cache only GET requests */
app.get('/info', cache('5 minutes'), (req, res) => {
  res.send('Info data');
});
📊

Quick Reference

FeatureUsageNotes
Cache-Control Headerres.set('Cache-Control', 'public, max-age=seconds')Controls browser/proxy caching duration
apicache Middlewareapp.get('/route', cache('duration'), handler)Caches GET responses in memory automatically
Cache DurationSpecify in seconds or human-readable (e.g., '10 minutes')Choose based on data freshness needs
Avoid Caching POSTDo not apply caching middleware to POST/PUT/DELETEThese routes change data and should not be cached
Cache InvalidationClear cache when data updatesUse apicache.clear() or custom logic

Key Takeaways

Use HTTP cache headers like Cache-Control to tell browsers how long to cache responses.
Middleware like apicache can simplify caching by storing responses in memory automatically.
Only cache GET requests and avoid caching routes that modify data.
Set cache duration carefully to balance speed and data freshness.
Clear or invalidate cache when underlying data changes to avoid stale content.