ETags help servers and browsers check if content has changed. This saves data by only sending updates when needed.
ETag and conditional requests in Node.js
res.setHeader('ETag', etagValue); if (req.headers['if-none-match'] === etagValue) { res.statusCode = 304; res.end(); } else { res.statusCode = 200; res.end(content); }
The ETag header is a unique string representing the content version.
The If-None-Match header is sent by the browser to check if the content changed.
const etagValue = '12345'; res.setHeader('ETag', etagValue); if (req.headers['if-none-match'] === etagValue) { res.statusCode = 304; res.end(); } else { res.statusCode = 200; res.end('Hello World'); }
const crypto = require('crypto'); const content = 'My content'; const etagValue = crypto.createHash('md5').update(content).digest('hex'); res.setHeader('ETag', etagValue); if (req.headers['if-none-match'] === etagValue) { res.statusCode = 304; res.end(); } else { res.statusCode = 200; res.end(content); }
This Node.js server sends an ETag header based on the content's SHA-256 hash. If the browser sends the same ETag back, the server replies with 304 Not Modified, saving data.
import http from 'http'; import crypto from 'crypto'; const server = http.createServer((req, res) => { const content = 'Welcome to my site!'; const etagValue = crypto.createHash('sha256').update(content).digest('hex'); res.setHeader('ETag', etagValue); if (req.headers['if-none-match'] === etagValue) { res.statusCode = 304; res.end(); } else { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end(content); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
ETags should be unique for each content version to work correctly.
304 status means 'Not Modified' and tells the browser to use cached content.
Always set Content-Type header when sending content.
ETags help browsers know if content changed to avoid re-downloading.
Use If-None-Match header to check ETag from browser requests.
Respond with 304 status to save bandwidth when content is unchanged.
Practice
ETag in HTTP responses in Node.js?Solution
Step 1: Understand what ETag represents
ETag is a unique identifier for a specific version of a resource, used to detect changes.Step 2: Identify its role in HTTP caching
Browsers use ETag to check if the resource changed since last download, avoiding unnecessary data transfer.Final Answer:
To help browsers check if the content has changed and avoid re-downloading unchanged data -> Option DQuick Check:
ETag purpose = avoid re-download [OK]
- Confusing ETag with encryption
- Thinking ETag sets content type
- Mixing ETag with cache expiration headers
Solution
Step 1: Recall Node.js HTTP response header syntax
Useres.setHeader(name, value)to set headers correctly.Step 2: Check the correct header name and value type
Header name is case-insensitive but usually 'ETag', and value must be a string.Final Answer:
res.setHeader('ETag', '12345') -> Option AQuick Check:
Set header with res.setHeader('ETag', value) [OK]
- Using incorrect method names like res.header or res.set
- Passing number instead of string as header value
- Trying to assign ETag directly as a property
const etag = 'abc123';
if (req.headers['if-none-match'] === etag) {
res.statusCode = 304;
res.end();
} else {
res.setHeader('ETag', etag);
res.end('Hello World');
}What will the server respond if the client sends header
If-None-Match: abc123?Solution
Step 1: Check the condition comparing If-None-Match header
The code comparesreq.headers['if-none-match']toetagwhich is 'abc123'. If equal, it sets status 304.Step 2: Understand HTTP 304 meaning
Status 304 means Not Modified, so no body is sent and client uses cached content.Final Answer:
Respond with status 304 and no body -> Option CQuick Check:
If-None-Match matches ETag = 304 no body [OK]
- Thinking 304 responses include body content
- Confusing 304 with 200 OK
- Ignoring the If-None-Match header check
const etag = 'xyz789';
if (req.headers['If-None-Match'] === etag) {
res.statusCode = 304;
res.end();
} else {
res.setHeader('etag', etag);
res.end('Content');
}What is the bug causing the ETag check to fail?
Solution
Step 1: Check header name case sensitivity in Node.js
Node.js lowercases all incoming header names, soreq.headers['If-None-Match']is undefined; correct isreq.headers['if-none-match'].Step 2: Confirm impact on ETag comparison
Because the header is undefined, the condition never matches, so 304 is never sent.Final Answer:
Header name case mismatch: 'If-None-Match' vs 'if-none-match' -> Option BQuick Check:
Headers lowercase in Node.js = use 'if-none-match' [OK]
- Using wrong case for header keys
- Thinking ETag must be numeric
- Misordering res.statusCode and res.end()
Solution
Step 1: Understand ETag generation
ETags should uniquely represent the current content, often by hashing the response body.Step 2: Use conditional request header to decide response
Comparereq.headers['if-none-match']with generated ETag; if equal, respond 304, else send content with new ETag.Final Answer:
Generate a hash of the response body, set it as ETag header, then compare with req.headers['if-none-match'] to decide 304 or 200 -> Option AQuick Check:
Hash body -> set ETag -> compare If-None-Match -> 304 or 200 [OK]
- Ignoring If-None-Match header
- Sending 200 always without checking ETag
- Misusing Cache-Control to replace ETag logic
Ready to prove it?
Pass the test and this pattern moves unknown
