How to process Phoenix conn after render before it is sent as a response

There are a bunch of operations you may want to perform before the rendered response in conn is sent to the client, such as minification. In this post I'll show you how to do it easily.

Table of contents

    Plug.Conn allows you to register a "before send" hook via register_before_send/2 function:

    require Logger
    
    Plug.Conn.register_before_send(conn, fn conn ->
      Logger.info("Sent a #{conn.status} response")
      conn
    end)

    It's very handy especially if you want to process conn with a plug. Here is an example from a simple minify_response library:

    defmodule MinifyResponse.HTML do
      alias MinifyResponse.HTML
    
      def init(opts \\ []), do: opts
    
      def call %Plug.Conn{} = conn, _ \\ [] do
        Plug.Conn.register_before_send(conn, &HTML.minify_body/1)
      end
    
      def minify_body(%Plug.Conn{} = conn) do
        case List.keyfind(conn.resp_headers, "content-type", 0) do
          {_, "text/html" <> _} ->
            body = conn.resp_body
                   |> Floki.parse
                   |> Floki.raw_html
    
            %Plug.Conn{conn | resp_body: body}
          _ ->
            conn
        end
      end
    end

    As you can see in this example, you can for instance use the register_before_send/2 function to process already rendered HTML. However, this is just an example, and there are many other use cases worth exploring.

    That's it! It's a very simple yet powerful trick. If you use it in your project to do some cool stuff - let me in the comments, I'd love to hear that!

    [Elixir Meetups by Curiosum - for who and when?](https://curiosum.com/blog/elixir-meetups-by-curiosum-for-who-and-when

    Szymon Soppa Web Developer
    Szymon Soppa Curiosum Founder & CEO

    Read more
    on #curiosum blog

    TOP Elixir media and resources

    Top Elixir Learning Media & Resources in 2022

    Regardless of whether you've only just heard of the Elixir programming language and would like to learn it, or if you're a seasoned developer with years of experience, you need adequate learning resources to ensure steady progress in your career - and just equally as important is the need to be up to date with what's new & trending in the functional

    Debugging Elixir Code: The Definitive Guide

    Debugging Elixir Code: The Definitive Guide

    Every application contains bugs, and even if it doesn't, it will. And even if you're not a notorious bug producer and your code quality is generally good, the conditions programmers work in are often suboptimal - you will often find yourself pulling your hair out over code written years ago by someone no longer involved in your project.