Skip to content

Cookbook: Pass Phoenix x request id header to upstream resources

Tymon Tobolski edited this page Nov 8, 2018 · 4 revisions

by @timbuchwaldt

defmodule MyAPI do
  use Tesla

  plug Tesla.Middleware.BaseUrl, "http://127.0.0.1:4000"

  def foo(client, login) do
    get(client, "/foo")
  end

  def client(conn) do
    Tesla.build_client [
      {PhoenixRequestIDMiddleware, conn}
    ]
  end
end

defmodule PhoenixRequestIDMiddleware do
  # requires tesla >= 1.0.0

  @behaviour Tesla.Middleware
  def call(env, next, conn) do
    {"x-request-id", id} = List.keyfind(conn.resp_headers, "x-request-id", 0)

    env
    |> Tesla.put_header("x-request-id", id)
    |> Tesla.run(next)
  end
end