Performance: ETag and conditional requests
This concept affects page load speed by reducing unnecessary data transfer and server processing for unchanged resources.
app.get('/file', (req, res) => { const fileContent = fs.readFileSync('file.txt'); const etag = generateETag(fileContent); if (req.headers['if-none-match'] === etag) { res.status(304).end(); } else { res.setHeader('ETag', etag); res.setHeader('Content-Type', 'text/plain'); res.send(fileContent); } }); function generateETag(content) { return 'W/"' + require('crypto').createHash('md5').update(content).digest('hex') + '"'; }
app.get('/file', (req, res) => { const fileContent = fs.readFileSync('file.txt'); res.setHeader('Content-Type', 'text/plain'); res.send(fileContent); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No ETag, always full response | N/A | N/A | High network and paint cost due to full reload | [X] Bad |
| ETag with conditional requests | N/A | N/A | Low network cost, faster paint due to cached content | [OK] Good |
ETag in HTTP responses in Node.js?res.setHeader(name, value) to set headers correctly.const etag = 'abc123';
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304;
res.end();
} else {
res.setHeader('ETag', etag);
res.end('Hello World');
}If-None-Match: abc123?req.headers['if-none-match'] to etag which is 'abc123'. If equal, it sets status 304.const etag = 'xyz789';
if (req.headers['If-None-Match'] === etag) {
res.statusCode = 304;
res.end();
} else {
res.setHeader('etag', etag);
res.end('Content');
}req.headers['If-None-Match'] is undefined; correct is req.headers['if-none-match'].req.headers['if-none-match'] with generated ETag; if equal, respond 304, else send content with new ETag.Pass the test and this pattern moves unknown