Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

04 - Phoenix crash course #4: Function plug

Learn how to create and use function plugs in Phoenix for middleware functionality

By Daniel Bergholz • Aug 19, 2025

Learn how to create and use function plugs in Phoenix for middleware functionality.

What’s a plug?

In Phoenix, a plug is like middleware: it receives a request connection (conn), does something with it, and passes it along.

How to make a function plug

  • A function plug takes two arguments: conn (connection) and opts (optional params)
  • Example: Create a check_promo_code plug that checks for a promo code in the URL query
  • If a valid promo code is found, assign a variable (e.g., promo: true) to the conn, making it accessible in your views
  • Use assign(conn, :key, value) to attach data; this can be rendered conditionally on the frontend using HEEx templates
  • Plugs are configured in the endpoint or the router and run at each request step

Elixir patterns

  • You can pattern match directly on conn.params for cleaner, more idiomatic code
  • Use multiple function heads for different match cases (e.g., promo code present vs. not present)

Custom plug parameters

  • You can pass options with your plug and access them via the opts argument

Frontend

  • Use @promo in HEEx to display a message if a valid promo code exists, and render conditionally with :if

Summary

This lesson covers building a custom function plug in Phoenix, assigning values to requests, conditionally rendering frontend content with HEEx, and using Elixir pattern matching for clean plug code.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz