How to Implement Conditional GET with Last-Modified
Serve Last-Modified validators, answer If-Modified-Since with honest 304 responses, handle clock skew, and verify the whole flow with curl.
On this page
Introduction
A conditional GET lets a client ask the server whether the copy it already holds is still current. Instead of downloading a full representation on every poll, the client sends a validator back and the server replies with a small 304 response when nothing changed. The Last-Modified header is the oldest and simplest validator in HTTP: the origin reports the instant a resource last changed, the client echoes it in If-Modified-Since, and the server compares the two timestamps. When the implementation is honest, a polling client that hits a large document once a minute transfers a few hundred bytes of headers instead of the whole payload.
Last-Modified is also the validator teams most often get subtly wrong. Serving the timestamp of the current request, returning 304 for a malformed date, or ignoring one-second precision all turn a bandwidth optimization into either a correctness bug or a silent no-op. This tutorial builds conditional GET around Last-Modified for a Node.js service, explains the comparison rule from the specification, shows how to combine it with an ETag, and ends with a curl script that proves the 200 and 304 paths.
How Last-Modified validation works
The protocol defines a request as conditional when it carries one of several precondition headers. For a read, the relevant pair is If-Modified-Since and If-None-Match. The server evaluates the precondition after it has selected the representation but before it serializes the full body. If the stored modification time is not newer than the date the client supplied, the server answers 304 Not Modified, includes the validator and cache headers again, and sends no payload. The client then refreshes the freshness clock of its stored copy from those headers.
The comparison has one detail that catches people out: Last-Modified and If-Modified-Since are transmitted with second resolution even though the underlying timestamp has finer precision. If the origin changed the resource at 12:00:00.900 and the client stored a Last-Modified of 12:00:00, a naive comparison of the full timestamps would say the resource is newer and defeat validation forever. The specification requires both values to be compared after truncating to whole seconds, so the stored time of 12:00:00 is considered equal to the client value and a 304 is returned.
Derive and format the validator
The validator must describe the representation, not the request. Load the last-changed timestamp from the data store or from the file metadata, and reuse that exact value on every replica. A timestamp generated at request time, or one that includes the response build moment, will almost never match what the client stored and disables caching. Format the value with the HTTP-date grammar, which is the IMF-fixdate style such as Sun, 06 Nov 1994 08:49:37 GMT. Never emit an ISO-8601 string with milliseconds or a local-time offset; intermediaries and clients parse only the HTTP-date format.
import { createServer } from 'node:http';
function httpDate(ms) {
return new Date(ms).toUTCString();
}
function handle(req, res) {
const updatedAt = 1700000000000; // from the data store
const lastModified = httpDate(updatedAt);
const since = req.headers['if-modified-since'];
const sinceMs = since ? Date.parse(since) : NaN;
const notModified =
Number.isFinite(sinceMs) &&
Math.floor(updatedAt / 1000) <= Math.floor(sinceMs / 1000);
const headers = {
'last-modified': lastModified,
'cache-control': 'public, max-age=60',
};
if (notModified) {
res.writeHead(304, headers);
res.end();
return;
}
const body = JSON.stringify({ updatedAt });
res.writeHead(200, { ...headers, 'content-type': 'application/json' });
res.end(body);
}
createServer(handle).listen(3000);
Answer If-Modified-Since safely
Parse the incoming header defensively. Date.parse returns a number for well-formed HTTP dates and NaN for garbage; treat NaN as absent and serve the full representation. A client that sends a syntactically valid but future date is also a special case: it is claiming to hold a copy from the future, which cannot be trusted, so the server should send the current body rather than claim a match it cannot verify.
Evaluate If-None-Match before If-Modified-Since. The specification states that when a request carries both preconditions, the ETag comparison takes precedence and the date is ignored. Many frameworks handle this automatically, but hand-written handlers frequently branch on the date first, which produces a wrong 304 when the ETag would have failed. Order the checks deliberately: tag first, date second, and let the stricter validator win.
Combine with an ETag and respect precedence
Last-Modified and ETag answer slightly different questions. The date says when the representation changed; the tag says whether the bytes are identical. A common mistake is to emit the date but forget the tag on a route whose payload is regenerated from aggregated data that can change without touching the source file. In that case the date never moves and clients keep a stale body. Emit both: the ETag from a hash of the final body, the Last-Modified from the data’s last write, and let either validator drive a 304. When they disagree, If-None-Match wins.
Reuse the same Cache-Control directive on the 304 as on the 200. A cache refreshes its stored metadata from the 304 response, so if the 304 omits max-age the client may fall back to heuristics and contact the origin more often. Keep the header set identical and only drop the payload.
import { createHash } from 'node:crypto';
function validators(body, updatedAt) {
const etag = '"' + createHash('sha256').update(body).digest('base64url').slice(0, 27) + '"';
return { etag, lastModified: new Date(updatedAt).toUTCString() };
}
function matches(req, { etag, lastModified }) {
const inm = req.headers['if-none-match'];
if (inm) return inm.split(',').map((v) => v.trim()).includes(etag);
const ims = req.headers['if-modified-since'];
if (!ims) return false;
const t = Date.parse(ims);
return Number.isFinite(t) && Date.parse(lastModified) <= Math.floor(t / 1000) * 1000;
}
Precision and clock pitfalls
Two clocks are involved: the origin clock that stamps the resource and the client clock that may have produced its own date. When both agree on UTC the one-second truncation is enough. When a reverse proxy or a load balancer rewrites dates, or when the origin runs with a skewed clock, the stored validator can appear to be in the future relative to the client, which forces a full response every time. Keep servers on synchronized time, and never let an edge component regenerate the Last-Modified value independently of the origin.
Content that changes more than once per second requires an ETag. A build system that rewrites a manifest on every deploy and a live feed that mutates constantly both defeat Last-Modified. In these cases the date is still useful as a human-readable diagnostic, but the correctness decision must come from byte hashing. Document which validator governs each route so a later refactor does not silently remove the one that matters.
Verify with curl and integration tests
Conditional logic fails quietly: a broken implementation returns 200 every time and the application still works, only slower. The fix is to assert the 304 path explicitly. Capture the validator from the first response, echo it back, and check that the status becomes 304 with a zero-byte body. Then send a deliberately newer date and confirm the server returns a full body.
LM=$(curl -sD - -o /dev/null http://localhost:3000/report | awk -F': ' 'tolower($1)=="last-modified" {sub(/\r/, "", $2); print $2}')
curl -s -o /dev/null -w 'status=%{http_code} size=%{size_download}\n' -H "If-Modified-Since: $LM" http://localhost:3000/report
curl -s -o /dev/null -w 'status=%{http_code} size=%{size_download}\n' -H "If-Modified-Since: Tue, 01 Jan 2030 00:00:00 GMT" http://localhost:3000/report
Conclusion
Conditional GET with Last-Modified turns a repeated download into a header exchange. Store a stable, representation-level timestamp, answer If-Modified-Since with second-resolution comparison, keep the header set identical on 200 and 304, and prefer If-None-Match when an ETag is present. Guard against clock skew and sub-second edits by pairing the date with a byte hash. Then prove the 304 path with a scripted curl sequence and an integration test that mutates the data between requests, because the failure mode of a broken validator is invisible until the bandwidth bill arrives.
As a self-check, measure the download size of the second request in your test suite and assert it is zero for a matching validator and greater than zero for a mismatched one. This single assertion catches the two most common regressions: serving the request-time clock as the validator, and dropping the 304 branch during a refactor.
Sources: MDN: Last-Modified header, MDN: HTTP conditional requests, RFC 9110: HTTP semantics.
FAQ
- Is Last-Modified worse than an ETag?
- Last-Modified has one-second granularity and cannot tell two changes within the same second apart, while an ETag hashes the exact bytes. Last-Modified is cheaper to produce and human-readable, so use it alone only when sub-second changes are impossible, otherwise pair it with an ETag.
- What if the client sends a future or malformed date?
- Ignore an unparsable value and serve the full 200. A future date must not force a 304, because the origin cannot prove the client already holds the current representation.
Report a problem with this articleOpens a pre-filled issue on GitHub.