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

Article autor
January 17, 2022
How to process Phoenix conn after render before it is sent as a response
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.
Elixir Newsletter
Expand your skills

Download free e-books, watch expert tech talks, and explore open-source projects. Everything you need to grow as a developer - completely free.

Table of contents

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.

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!

Work with a team that keeps learning and building better software every day.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

Skip file changes tracking in git

So, you’re changing this one file for local development purposes only. Maybe it’s config, maybe some source file, but one thing is certain - you don’t want those changes to be committed. And what’s worse, .gitignore doesn’t work.

How to get the struct type in Elixir

So you don’t know what’s the type of struct you’re passing somewhere? Maybe it can be one of few types and you have to distinguish them? Or any other reason… But it’s about checking the struct type. Just use one of the coolest Elixir features - pattern matching!

How to check if a set contains exact values with Jest in JS?

TLDR: With jest-extended package you can write: expect([...set]).toIncludeSameMembers([value1, value2]);. If you are looking to a native, but longer solution scroll down a bit.