Skip to content

Allow overriding etag function in application #2129

@ashi009

Description

@ashi009

Current express calculates etag via utils.etag(), which is a private function, and could be overrided by:

  1. res.set('etag', 'etag value') before res.send(), or
  2. override by wrapping res.send() by setting res.set('etag', 'etag value') before forward arguments to the old res.send().

These two method works, but all come with catches:

  1. require to call res.set() explicitly in every route, which is very inconvenient;
  2. new res.send() must handle all supported method signatures, to generate etag correctly based on modified body. Which comes with performance penalty and may lead to forward compatibility issue.

So a more clean solution is to expose etag on application and response level, which allows override by doing:

app.etag = function(buf) {
  return '"' + crc32c.calculate(buf) + '"';
};

or

function strongEtag(buf) {
  return '"' + crypto.createHash('sha1').update(buf).digest('hex') + '"';
}

function strongEtagMiddleware(req, res, next) {
  res.etag = strongEtag;
  next();
}

app.get('/critical', strongEtagMiddleware, function(req, res) {
  res.send('critical data');
});

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions