Cache invalidation helps keep stored data fresh and accurate by removing or updating old information.
0
0
Cache invalidation strategies in Express
Introduction
When you update data on the server and want users to see the latest version.
When cached data becomes outdated after a certain time.
When you want to clear cache after a user logs out to protect privacy.
When you want to improve performance but avoid showing stale data.
When you want to control cache behavior for different types of content.
Syntax
Express
app.use((req, res, next) => {
res.set('Cache-Control', 'no-cache');
next();
});This example shows how to set HTTP headers to control cache behavior in Express.
You can customize cache rules using different Cache-Control directives.
Examples
This tells browsers not to store any cache at all.
Express
res.set('Cache-Control', 'no-store');
This allows caching for 60 seconds before invalidation.
Express
res.set('Cache-Control', 'max-age=60');
This allows shared caches to store the response for 5 minutes.
Express
res.set('Cache-Control', 'public, max-age=300');
This caches data only for the user and requires revalidation before use.
Express
res.set('Cache-Control', 'private, no-cache');
Sample Program
This Express app sets a cache expiration of 10 seconds for all responses. The homepage shows the current time. If you refresh within 10 seconds, the cached response may be used. After 10 seconds, the cache invalidates and the server sends fresh data.
Express
import express from 'express'; const app = express(); // Middleware to set cache control headers app.use((req, res, next) => { // Invalidate cache after 10 seconds res.set('Cache-Control', 'public, max-age=10'); next(); }); app.get('/', (req, res) => { res.send(`Current time: ${new Date().toISOString()}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Cache-Control headers are the main way to control cache invalidation in HTTP.
Use short max-age values for frequently changing data.
Remember to test cache behavior using browser DevTools Network tab.
Summary
Cache invalidation keeps data fresh by controlling how long cached data is valid.
Express apps use Cache-Control headers to set cache rules.
Choose the right strategy based on how often your data changes.