How do I return 304 Unmodified status with Express.js?
There is no need to use any third-party module like etag
. Express handles the logic behind etag
and no need to write code.
Enable
etag
in Express. In the example below, we are using strong etags.// Use string ETag app.set('etag', 'strong');
Build your response in the
GET
method:app.get('/my-data', (req, res) => { ... res.append('Last-Modified', (new Date(lastModifiedStringDate)).toUTCString()); return res.send(response); }
Voilá, Express will send either the content of your response 200 OK
or an empty body with response 304 Not Modified
.
Clients submitting requests with header If-None-Match
will receive HTTP 304 Not Modified
, if the etag
has not changed.
Make sure your requests do not send Cache-Control: no-cache
. Tools like Postman per default do send the header Cache-Control: no-cache
, which invalidates the Express ETag (no cache is no cache after all). You can change this behaviour by toggling it in Postman's settings.
We are adding the Last-Modified
as a plus in our response. You do not need to use it as we do. But Express will also respect the If-Modified-Since:
header using similar logic (temporal), instead of content (Etags
).
Am I supposed to use custom generated etags and cache these on the server, then compare request etags with this cache?
Yes, you can use something like the etag npm module which can take a Buffer or string and provide you with a strong etag value: res.setHeader('ETag', etag(body))
. If you are storing modification dates in your database then you could also simply send those down to the client in the form of a Last-Modified
header. In that case the client would end up sending an If-Modified-Since
in subsequent requests which you could then use to compare to the modification column of the resource being requested.
In either case you will be responsible for responding with the appropriate status code, headers, and body.
If you're serving static files from the actual file system then you could just use the serve-static express middleware which will automatically provide the correct caching behavior.