How to reposen 405 of TRACE response in elixir ( Phoenix Framework )

I want to handle the any TRACE method api call to 405 status code, “Unhandle Method” with a response body. Now it is behave like elixir default behaviour is itself by return 501 NOT IMPLEMENTED. I already tried adding plug that handle and response the 405 status code but when I call the api from postman with the TRACE method its not even reach to my api code.

To handle the TRACE HTTP method and return a 405 status code with a custom response body in an Elixir/Phoenix application, you’ll need to configure your router or use a plug to intercept requests that match the TRACE method before they reach the default behavior.

Here’s how you can set it up:

Step 1: Create a Plug to Handle TRACE Requests

You can create a custom plug that will catch TRACE requests and return a 405 status code:

defmodule YourAppWeb.Plugs.TraceHandler do
  import Plug.Conn

  @response_body "Method Not Allowed"

  def init(default), do: default

  def call(%Plug.Conn{method: "TRACE"} = conn, _opts) do
    conn
    |> put_resp_content_type("text/plain")
    |> send_resp(405, @response_body)
    |> halt()
  end

  def call(conn, _opts), do: conn
end

Step 2: Add the Plug to Your Endpoint

You need to add this plug to your endpoint.ex file, so it gets invoked for every request:

defmodule YourAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :your_app

  # Other plugs...

  plug YourAppWeb.Plugs.TraceHandler

  # Remaining plugs and code...
end

Step 3: Testing the Configuration

After adding the plug, make sure to restart your Phoenix server. Then, when you make a TRACE request to your application, it should now respond with a 405 status code and the body “Method Not Allowed”.

Step 4: Ensure No Conflicting Rules

If you still encounter the 501 NOT IMPLEMENTED error, ensure that there are no other configurations or middleware that might be intercepting the TRACE method requests before they reach your custom plug.

Summary

By following these steps, your application should be able to handle TRACE requests appropriately and respond with a 405 status code. If you encounter any issues, make sure to check the order of plugs in your endpoint and that your application is properly restarted to reflect changes.