Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

05 - Phoenix crash course #5: Module plug

Learn how to create and use module plugs in Phoenix for organized, reusable middleware functionality

By Daniel Bergholz • Aug 19, 2025

Learn how to create and use module plugs in Phoenix for organized, reusable middleware functionality.

What’s a module plug?

A module plug is a reusable module in Phoenix that processes each request, typically for more organization and code reuse than function plugs.

In this episode

  • Builds a form for users to select their preferred console (PC, Xbox, PlayStation, Nintendo)
  • Creates a SetConsole module plug that:
    • Reads the console selection from the URL or cookies
    • Assigns the selected console to the connection (so the choice is available in views)
    • Saves the console choice to a cookie for persistence between page reloads
    • Uses a default console if none is provided
    • Includes validation: only allows valid console names; falls back to default if invalid
  • Shows how to wire the module plug into the Phoenix router pipeline for all browser requests
  • Makes sure assign and put_resp_cookie are imported from Plug.Conn
  • Console selection is reflected on all pages; invalid values do not pollute cookies or assigns

Best practice highlight

Using guards and pattern matching, only valid console choices are accepted for assignment and cookies; others revert to the default.

Why use module plugs?

  • Keeps code more organized and maintainable (usually kept in a plugs/ folder)
  • Preferred for most structured or multi-function plug logic

Summary

This video demonstrates building a stateful feature (selected console) for web visitors using module plugs, cookies, and assignment in Phoenix—covering common edge cases and best practices for plug architecture.

Related

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