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: 2024-05-29

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

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

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
  # ...

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:

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

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.