ETags help servers and browsers check if content has changed. This saves data by only sending updates when needed.
0
0
ETag and conditional requests in Node.js
Introduction
When you want to reduce data sent between server and browser for faster loading.
When your website has static files like images or scripts that rarely change.
When you want to improve user experience by loading pages faster.
When you want to save bandwidth on your server.
When you want to implement caching in your Node.js web app.
Syntax
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.
Examples
Sends 'Hello World' only if content changed; otherwise sends 304 Not Modified.
Node.js
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'); }
Generates ETag using MD5 hash of content for better uniqueness.
Node.js
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); }
Sample Program
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.
Node.js
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/'); });
OutputSuccess
Important Notes
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.
Summary
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.