Never switch on session variant data in publicly cached resources

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the caching category.

Last Updated: 2021-05-16

I had the following code in my _header.html.erb component.

<li>
  <%= link_to "Cart: (Empty)", cart_path, class: "cart-link #{current_order && 'red'}" %>
</li>

This header was used throughout the application, including inside pages HTTP-cached publicly:

def about_us
  # Adds Cache-Control headers
  expires_in 12.hours, public: true
  # ...
end

The issue, here, is that the cart link will randomly have the class red or not depending on whether the first person who happens to request that page during each 12 hour period happened to have a current order.

The fix was to remove the view logic that modified the UI based on the current user's state:

<li>
  <%= link_to "Cart: (Empty)", cart_path, class: "cart-link red" %>
</li>

You can use instead use JavaScript to dynamically modify the default page based on session data, as needed. This allows you to continue caching the page with public caches.