0
0
Node.jsframework~8 mins

Setting response headers in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Setting response headers
MEDIUM IMPACT
Setting response headers affects how quickly the browser can start rendering content and how efficiently resources are cached or processed.
Setting HTTP headers for caching and content type in a Node.js server
Node.js
const http = require('http');
http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Cache-Control', 'public, max-age=31536000');
  res.end('<h1>Hello</h1>');
}).listen(3000);
Enables browser caching for one year, reducing repeated network requests and speeding up load.
📈 Performance GainReduces LCP by avoiding unnecessary network fetches on repeat visits.
Setting HTTP headers for caching and content type in a Node.js server
Node.js
const http = require('http');
http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('Cache-Control', 'no-cache');
  res.end('<h1>Hello</h1>');
}).listen(3000);
Using 'no-cache' disables caching, causing browsers to re-fetch resources every time, increasing load times.
📉 Performance CostIncreases LCP by causing repeated network requests, blocking rendering longer.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
No caching headers or 'no-cache'N/AN/ABlocks rendering until network response[X] Bad
Proper Content-Type and long max-age cachingN/AN/AAllows fast rendering from cache[OK] Good
Rendering Pipeline
Response headers are sent before the body, informing the browser how to handle the content and caching. Proper headers reduce network delays and improve rendering start time.
Network
Critical Rendering Path
Cache
⚠️ BottleneckNetwork latency caused by inefficient caching headers
Core Web Vital Affected
LCP
Setting response headers affects how quickly the browser can start rendering content and how efficiently resources are cached or processed.
Optimization Tips
1Always set Content-Type header correctly to avoid rendering delays.
2Use Cache-Control with appropriate max-age to enable browser caching.
3Set all headers before sending the response body to ensure proper browser handling.
Performance Quiz - 3 Questions
Test your performance knowledge
Which response header setting improves repeat page load speed the most?
AContent-Type: text/plain
BCache-Control: no-cache
CCache-Control: public, max-age=31536000
DNo headers set
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, click a resource, check 'Response Headers' for Cache-Control and Content-Type values.
What to look for: Look for Cache-Control with max-age or public directives and correct Content-Type to confirm good header setup.