In this lesson, you will learn how to reduce server load and save bandwidth by using ETags to avoid sending redundant data to the client.
Understanding the Problem
Imagine your server hosts a large JSON file that doesn't change very often. Every time a client requests this file, your Node.js server reads it from disk and sends the entire body over the network. This is wasteful if the client already has the most recent version of that file.
What is an ETag?
An ETag (Entity Tag) is a unique identifier assigned to a specific version of a resource. Think of it as a "fingerprint" or a hash of your data.
- The Server’s Job: When the client first requests the file, your server calculates a hash (like an MD5 or SHA) of the content and sends it back in a header called
ETag. - The Client’s Job: The client saves this ETag.
- The Conditional Request: The next time the client asks for that file, it sends the
ETagit stored in a header calledIf-None-Match.
Implementation in Node.js
If your server receives an If-None-Match header, it compares that value to the current hash of the resource. If they match, the content hasn't changed. Instead of sending the file again, your server sends an empty response with the status code 304 Not Modified.
const etag = 'v1-hash-12345'; // Imagine this is generated from your file
function handleRequest(req, res) {
const clientEtag = req.headers['if-none-match'];
if (clientEtag === etag) {
// Content hasn't changed!
res.writeHead(304);
res.end();
} else {
// Content is new or different
res.setHeader('ETag', etag);
res.writeHead(200);
res.write(largeDataBuffer);
res.end();
}
}
By returning 304 Not Modified, you skip the time-consuming process of streaming the file body, significantly reducing network traffic and CPU usage. The client automatically reuses its cached copy once it receives the 304 response.
Key Takeaway: Using ETag and If-None-Match allows the server to tell the client "nothing has changed" without re-sending the data, saving both bandwidth and processing time.