Skip to content

Instantly share code, notes, and snippets.

@eproxus
Last active November 4, 2023 18:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eproxus/bd40f3a06e2c78dea539d2ba0471e36f to your computer and use it in GitHub Desktop.
Save eproxus/bd40f3a06e2c78dea539d2ba0471e36f to your computer and use it in GitHub Desktop.
How to Create a Cowboy Middleware

How to Create a Cowboy Middleware

Add an entry to the middlewares. Usually you want to keep the standard Cowboy handlers afterwards, but you can replace them if you want.

{ok, Pid} = cowboy:start_clear(ListenerName,
    [{port, Port}],
    #{
        env => #{dispatch => Dispatch},
        middlewares => [my_middleware, cowboy_router, cowboy_handler]
    }
),

A middleware implements the behavior cowboy_middleware.

Caveats

  • You cannot change a response after it has been sent. For example, if you add a middleware after the generic cowboy_handler middleware. If a previous middleware has called the cowboy_req:reply/4 function the response has already been sent on the wire. For that purpose you need to use a stream handler instead.
-module(my_middleware).
-behaviour(cowboy_middleware).
-export([execute/2]).
execute(Req, Env) ->
io:format("~p request~n", [cowboy_req:method(Req)]),
{ok, Req2, Env}.
@monstermichl
Copy link

Thanks for showing, what the official documentation doesn't :)

@weaversam8
Copy link

Do you have a source for this?

Middlewares are "deprecated"

It appears to me that stream handlers and middleware accomplish different goals. Middleware are a feature that the default cowboy_stream_h stream handler supports, right? Where you could hook in between, say, the router and the underlying application handler. If you wanted to do that with a stream handler, you'd need to reimplement the routing logic...

@eproxus
Copy link
Author

eproxus commented Nov 4, 2023

Do you have a source for this?

Middlewares are "deprecated"

Trying to find now where I read something about this but cannot remember. I thought it was somewhere in the official docs, repo or some comment from Loïc, but alas…

There is the slight possibility that I mixed it up with hooks which were explicitly deprecated in favor of stream handlers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment