We blog about web and native apps

Looking for extraordinary Elixir and Ruby developers? Visit Byteflip to find out more.
Phoenix and LiveView without cookies

As I’ve written before, our website and blog are written with the Phoenix Framework and use LiveView. When migrating to Phoenix 1.5.1, I had 1 special requirement: the site should work without cookies.

What’s wrong with cookies you ask? With the actual cookies - nothing, they work just fine. The problem is with the regulation around it. You’ve probably noticed the cookie consent banners all across the internet. They should notify the user about the cookies used and give an option to opt-out.

The only cookie that Phoenix creates by default is the session cookie. Does it require a cookie consent? Who knows ¯\_(ツ)_/¯. I don’t want to build a consent popup just to be safe, but I also don’t want the company to get in trouble if it was actually needed.

The safe approach I decided to take is to get rid of the session cookie. Our site doesn’t really need it in the first place - we don’t store anything in the session. And if there are no cookies, then we don’t need any cookie consent banners either. Win win. Let’s get to it.

Remove session cookies from Phoenix

To do that, we need to:

  1. Edit router.ex and remove everyting related to session.
  • plug :fetch_session
  • plug :fetch_live_flash
  • plug :protect_from_forgery
  1. Edit endpoint.ex.
  • Replace
      socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
    with
      socket "/live", Phoenix.LiveView.Socket
  • Remove plug Plug.Session, @session_options.
  • Remove the @session_options module attribute.
  1. Edit root.html.leex and remove the <%= csrf_meta_tag() %>.
  2. Edit app.js.
  • Replace
      let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
      let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
    with
      let liveSocket = new LiveSocket("/live", Socket)

And this should do it. If you start the server and open the browser console, you’ll see no more cookies being created.

Warning: These instructions remove cross-site request forgery protection. Our site is read-only and has no forms. If you have any forms, login area, any url that modifies state on the server - think twice before applying these examples. You probably then do need sessions and cookies.