1533 South Street · Floor One · Philadelphia, PA 19146 · 215.546.6496

Serving a localized, cached navigation menu with cookies and javascript

OK, so the title of this blog post is some fancy jargon to succinctly explain an issue I ran into when dealing with a very specific client request.

This particular client has a national organization with two local chapters. All three of these sites get rolled into the same Drupal install - this part was really easy with Organic Groups. The interesting part is the idea that the Drupal site would remember the user's local chapter, and modify the navigation menu accordingly. So, when the user first visits the site, they click on "News" in the main navigation and choose their local chapter before they see the news relevant to that chapter. On subsequent visits, clicking on "News" will take them directly to their localized news.

In theory this seemed like a bit of a challenge, but more or less straightforward. I would use a cookie and some clever logic to manipulate the navigation menu before serving it. The issue with this is that we still want the site to perform under load, so we're serving pages from behind a cache. Do you see where I'm going with this?

Caching means that we always have to serve the same content to any anonymous user. Obviously we want our scheme to serve locally-relevant news to apply to anonymous as well as authenticated users. We have to somehow make the same link serve different content, even though the request will never hit the Drupal server in order to perform any cookie-based logic.

Enter the magic of Javascript. We move the logic to set and read cookies that would typically reside Drupal-side into Javascript. Drupal serves the same, cached page to anonymous users. With the help of jQuery, we append the value of the user's cookie to the link URL from which we want to serve localized content. All of a sudden, we're serving dynamic navigation links without any server-side performance hit.*

In a world of rich web apps, this may sound like old news to veteran Javascript junkies. But as far as I can tell this is relatively new ground for Drupal. Maybe this goes to show how much catching up Drupal has to do.

* - Usability wonks and anti-javascript crusaders are jumping up and down screaming right now, but do not fret. The javascript-free user doesn't get the cookie in the first place, and gets presented with a form to choose their local chapter when they request what would lead directly to a localized page.