This blog is part of our Rails 5 series.
ETag, short for entity tag, is a part of HTTP header and is used for web cache validation. ETag is a digest of the resource that uniquely identifies specific version of the resource. This helps browser and web servers determine if resource in the browser’s cache is exactly same as the resource on the server.
Strong v/s Weak ETags
ETag supports strong and weak validation of the resource.
Strong ETag indicates that resource content is same for response body and the response headers.
Weak ETag indicates that the two representations are semantically equivalent. It compares only the response body.
Weak ETags are prefixed with
thus one can easily distinguish between Weak ETags and Strong ETags.
W3 has an example page to illustrate how ETag matching works.
When server receives a request, it returns an ETag header as part of HTTP response.
This ETag represents state of the resource.
For the subsequent HTTP requests,
client sends this ETag via
If-None-Match header to identify if the resource is changed or not.
The server will compare the current ETag and the one sent by the client.
If ETag matches, server responds with
304 Not modified.
This means resource content in the client’s cache is up-to-date.
If resource is changed, server will send updated resource along with the new ETag.
Let’s see it in action.
ETags in Rails 4.x
Rails 4.x generates strong ETags by default i.e without
We are making first request to the server.
For the next request,
we will send ETag that was sent
by the sever.
And notice that server
304 Not Modified.
Rails 5 sets Weak ETags by default
In Rails 5, all ETags generated by Rails will be weak by default.
Now for the second request, server will return
304 Not Modified response as before,
but the ETag is weak ETag.
Why this change?
Rails does not perform strong validation of ETags as implied by strong ETags spec. Rails just checks whether the incoming ETag from the request headers matches with the ETag of the generated response. It does not do byte by byte comparison of the response.
This was true even before Rails 5. So this change is more of a course correction. Rack also generates weak ETags by default because of similar reasons.
How to use strong ETags in Rails 5
If we want to bypass default Rails 5 behavior to use strong ETags then we can do by following way.
This will generate strong Etag i.e without