37
votes

As a newcomer to both Elixir and the web domain in general (no web framework experience) I would like to know, what is Plug? As I understand it Cowboy is a web server (albeit in Erlang, not Elixir) and Phoenix is a framework for building web apps, but where does Plug come in? Is it an abstraction layer between the two or perhaps a plug-in system in the same abstraction layer as Phoenix?

3

3 Answers

55
votes

Is it an abstraction layer between the two

Yes, exactly! Plug is meant to be a generic adapter for different web servers. Currently we support just Cowboy but there is work to support others.

Plug also defines how different components should be plugged together. Similar to Rack in Ruby, WSGI in Python, Ring in Clojure, and so on.

3
votes

Think of plugs as a pipeline of instructions. The intention of plugs is to take in a conn, modify it and then return the modified conn. You can use plugs for tons of things from attaching headers to requests to verifying that a user is authenticated before rendering certain things. In my current project, I am using plugs to handle the construction of my requests as well as handling authentication.

1
votes

I’ve actually wrote a small deep-dive into Plug and Cowboy and how they work under the hood which you can read here but the basic summary would be the following:

Cowboy is the actual web-server that parses and processes any incoming and outgoing request written in Erlang. Cowboy works in tandem with Ranch which handles the incoming socket connections and manages the TCP Protocol

Plug is nothing more than a specification to help you build web endpoints. It gives you the tools to handle HTTP requests, set status code, send responses back, etc

A way that helps me reason about this whole system is to think of Plug and Cowboy as the underlying plumbing to Phoenix.