Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active April 10, 2021 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samarpanda/a97c2e66029324e115255367de8339b9 to your computer and use it in GitHub Desktop.
Save samarpanda/a97c2e66029324e115255367de8339b9 to your computer and use it in GitHub Desktop.
Express - ETag fix for multiple servers

Express Etag fix (Multiple servers)

Etag uses information from file system stat. Including the modified time similar to nginx & apache. This can't calculate the hash of the contents. Doing so that would require reading the file from the file system twice for every single request scope.

Files usually have slightly different modification timestamp between multiple servers. Similarly apache/nginx would do the same.

Simple way to calculate ETag for the static files:

app.use(express.static(path.join(__dirname, 'public', {
  setHeaders: setStaticETag
})));

function setStaticETag(res, path, stat){
  const etag = ''; // Custom logic to calculate ETag
  res.setHeader('ETag', etag);
}

Basic curl command to verify before and after the fix

curl -I http://<SERVER_IP_1>/static/img.jpeg
ETag: "1234-2323453245"

curl -I http://<SERVER_IP_2>/static/img.jpeg
ETag: "1234-2323453245"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment