50

Expressjs automatically send etags. I would like to know how the etag is generated..is it based on the content that is generated dynamically by the get routine. or is there way I can mainpulate it, by not even going through the process of generating the content(dynamic content - from DB) and pass back etag as same.

may be a middleware which start with just checking if it is valid session id and pass back the same etag that the client gives or may be based of the url + session id..that way it will be unique. and end the request there rather going through the whole db call and all those stuff. in which case I would need to know the client is making a 304 call.

I could go with the expires tag.but when the session is over. if somebody is opening the url it should not allow. so I am thinking the etag should be based of the session id as well. how does if modified can work in this dynamic content scenario. can it be used.

coool
  • 7,725
  • 12
  • 50
  • 77

1 Answers1

54

At the time of writing (8th July 2014), weak ETags are generated using CRC32 (source) and strong ETags are generated using MD5 (source).

Based on what one of the contributors to Express says, you can specify whether to use the strong or weak ETags by:

app.enable('etag') // use strong etags
app.set('etag', 'strong') // same
app.set('etag', 'weak') // weak etags

It looks like you can also specify your own custom function to do the ETags like so:

app.set('etag', function(body, encoding){ /* return valid etag */ });

The NPM package fresh is also worth looking at, as it's used in Express for freshness checking (source1, source2).

As for your application, remember that you can override any response headers e.g. res.set('etag', 'my-awesome-etag-value') before invoking res.send() (or similar function). Further discussion (including advantages and disadvantages) can be found here: https://github.com/visionmedia/express/issues/2129#issue-34053148

stellarchariot
  • 2,672
  • 17
  • 28
  • 15
    I'll like to point out that according to the express 4.X [docs](http://expressjs.com/api.html#app.set), the default etag type is `weak` when enabling etags. – bakavic Oct 07 '15 at 03:24
  • 4
    Update: ETag generation is done by to the [jshttp/etag](https://github.com/jshttp/etag) module. Version 1.7 (2015-06-08) always uses MD5 instead of CRC32 because CRC32 is prone to collision. The next version will always use SHA1 instead of MD5 because MD5 is not FIPS-compliant. Finally, the only thing "weak" does is set the "W/" prefix on the ETag. While express defaults to "W/", it's technically a strong ETag because the hash is calculated on the body bytes as opposed to its semantic content. If you're able to implement weak ETag calcs for your app, it's a potentially big perf boost. – ZachB Feb 16 '17 at 02:28