0
0
Node.jsframework~8 mins

ETag and conditional requests in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: ETag and conditional requests
MEDIUM IMPACT
This concept affects page load speed by reducing unnecessary data transfer and server processing for unchanged resources.
Serving static files efficiently with caching
Node.js
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') + '"';
}
Sends 304 Not Modified when content is unchanged, avoiding full data transfer and speeding up load.
📈 Performance GainReduces bandwidth usage and improves LCP by skipping full resource download on cache hits.
Serving static files efficiently with caching
Node.js
app.get('/file', (req, res) => {
  const fileContent = fs.readFileSync('file.txt');
  res.setHeader('Content-Type', 'text/plain');
  res.send(fileContent);
});
Always sends full file content on every request, causing unnecessary data transfer and slower load times.
📉 Performance CostBlocks rendering until full file is downloaded every time, increasing LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No ETag, always full responseN/AN/AHigh network and paint cost due to full reload[X] Bad
ETag with conditional requestsN/AN/ALow network cost, faster paint due to cached content[OK] Good
Rendering Pipeline
ETag and conditional requests reduce the amount of data the browser must download and parse, speeding up the critical rendering path by avoiding unnecessary resource loading.
Network
Style Calculation
Layout
Paint
⚠️ BottleneckNetwork transfer and resource loading
Core Web Vital Affected
LCP
This concept affects page load speed by reducing unnecessary data transfer and server processing for unchanged resources.
Optimization Tips
1Always generate and send ETag headers for cacheable resources.
2Check the If-None-Match header to respond with 304 when content is unchanged.
3Avoid sending full resource data when the client already has the latest version.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using ETag with conditional requests?
AImproves CSS selector matching speed
BIncreases server CPU usage by recalculating content
CReduces data transfer by avoiding sending unchanged resources
DReduces JavaScript execution time
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and look for 304 status codes in the resource list.
What to look for: Resources returning 304 Not Modified indicate successful conditional requests and efficient caching.