418 words, 3 min read

Are you looking to improve the performance of your Elixir Phoenix application? Adding support for ETags (Entity Tags) is a fantastic way to do this. ETags are HTTP headers that provide a validation mechanism for the browser's cache, helping to reduce unnecessary data transfers and server load. Instead of re-sending the same content every time a user requests a page, the server can simply tell the browser, "Your cached version is still good!"

Fortunately, integrating this functionality is incredibly easy thanks to the etag_plug library. Here's a quick guide on how to get it set up in your Phoenix project.

The first step is to add etag_plug to your project's dependencies. Open up your mix.exs file and add the following line to the deps function:

def deps do
[
{:etag_plug, "~> 1.0"}
]
end

After you've saved the file, remember to fetch the new dependency by running mix deps.get in your terminal.

Once installed, you can enable ETag support by simply adding the plug to your endpoint.ex file. For most use cases, the default configuration is perfect and requires just one line of code.

plug ETag.Plug

This will automatically generate ETags for GET requests with a status code of 200 (OK).

If you need more control, you can pass options to the plug. For example, if you want to generate ETags for a variety of HTTP methods and status codes, your configuration might look something like this:

plug ETag.Plug,
methods: ["GET", "HEAD"],
status_codes: [:ok, 201, :not_modified]

For even more fine-grained control, you can configure etag_plug globally within your config/config.exs file. This is useful for setting the default behavior across your entire application.

config :etag_plug,
generator: ETag.Generator.SHA1,
methods: ["GET"],
status_codes: [200]

Here's a breakdown of the key configuration options:

  • generator: This option specifies which algorithm the plug should use to generate the ETag. The library ships with several built-in generators:

    • ETag.Generator.MD5
    • ETag.Generator.SHA1 (the default)
    • ETag.Generator.SHA512

    You can also create your own custom generator by implementing the ETag.Generator behavior.

  • methods: This is a list of HTTP method strings (e.g., "GET", "POST", "HEAD") for which ETags should be generated. The default is ["GET"].

  • status_codes: This option takes a list of integers or status atoms (like :ok) and determines which HTTP status responses will have ETags generated. The default is [200].

With these simple steps, you can add powerful caching support to your Phoenix application and provide a faster, more efficient experience for your users. For detailed documentation and more advanced usage, be sure to check out the official etag_plug HexDocs page.