Beginner LevelExpress JS
How do req.fresh and req.stale determine if client browser cache is valid using ETag and If-None-Match?
❓ Interview Prompt: Explain HTTP cache validation, req.fresh vs req.stale, ETag headers, and returning 304 Not Modified.
Express automatically calculates response ETag hashes. On subsequent requests, the client sends an 'If-None-Match' header containing the cached ETag.
Cache Properties:
•
'req.fresh': Returns 'true' if the client's cached ETag matches the server ETag (cache is fresh).
•
'req.stale': Returns 'true' if cache is stale or missing.
•
When 'req.fresh' is 'true', server can execute 'res.status(304).end()' to skip sending the response body!
Code Implementation Example
javascript
import express from 'express';
const app = express();
app.get('/api/cached-resource', (req, res) => {
if (req.fresh) {
// Client cache is still valid! Return 304 Not Modified and skip body payload
return res.status(304).end();
}
res.json({ data: 'Fresh Payload Content' });
});💡Skipping payload transmission using req.fresh and 304 Not Modified.
🎯 Interview Key Takeaway
Check req.fresh to return 304 Not Modified when client ETag caches match, saving bandwidth.
#req.fresh#ETag#Caching#Beginner
Back to all Express JS Questions→