Home  Web-development   How etag wo ...

How ETag works in browser caching

Let's walk through an example of how ETag works with HTTP caching.

Scenario

Let's say we have a web application that serves a user profile picture. The URL for this picture is https://example.com/profile.jpg.

Initial Request

  1. First Request by Browser:

    The browser makes an initial request to the server to fetch the profile picture.

    GET /profile.jpg HTTP/1.1
    Host: example.com
    
  2. Server Response:

    The server responds with the profile picture and includes an ETag header.

    HTTP/1.1 200 OK
    Content-Type: image/jpeg
    Content-Length: 12345
    ETag: "abc123"
    

    The ETag value "abc123" uniquely identifies the version of the resource.

Subsequent Requests

  1. Second Request by Browser:

    The browser caches the profile picture along with its ETag. The next time the browser requests the same profile picture, it includes the ETag in the request headers to check if the resource has changed.

    GET /profile.jpg HTTP/1.1
    Host: example.com
    If-None-Match: "abc123"
    
  2. Server Response (Resource Not Modified):

    If the resource has not changed, the server responds with a 304 Not Modified status, indicating that the cached version is still valid. The response does not include the resource body, saving bandwidth.

    HTTP/1.1 304 Not Modified
    ETag: "abc123"
    

    The browser continues to use the cached version of the profile picture.

Handling Resource Changes

  1. Server Response (Resource Modified):

    If the resource has changed, the server responds with a 200 OK status and includes the new version of the resource along with a new ETag.

    HTTP/1.1 200 OK
    Content-Type: image/jpeg
    Content-Length: 12346
    ETag: "def456"
    

    The browser caches the new version of the resource and the new ETag value.

Example Workflow

Here’s a full example demonstrating the ETag workflow:

Initial Request and Response:

  1. Initial Request:

    GET /profile.jpg HTTP/1.1
    Host: example.com
    
  2. Initial Response:

    HTTP/1.1 200 OK
    Content-Type: image/jpeg
    Content-Length: 12345
    ETag: "abc123"
    

Subsequent Request and Response (Not Modified):

  1. Subsequent Request:

    GET /profile.jpg HTTP/1.1
    Host: example.com
    If-None-Match: "abc123"
    
  2. Not Modified Response:

    HTTP/1.1 304 Not Modified
    ETag: "abc123"
    

Subsequent Request and Response (Modified):

  1. Subsequent Request:

    GET /profile.jpg HTTP/1.1
    Host: example.com
    If-None-Match: "abc123"
    
  2. Modified Response:

    HTTP/1.1 200 OK
    Content-Type: image/jpeg
    Content-Length: 12346
    ETag: "def456"
    
Published on: Aug 01, 2024, 12:35 AM  
 

Comments

Add your comment