Boris Guéry

Hacking the web since 1997.

Mobile and Tablet Device Detection With Varnish

I recently had to work on our mobile website, using a RESS strategy. All worked great until I had to determine if the connecting device was a mobile, a tablet, or a generic desktop web browser.

It could have been simple by using some server-side framwework like MobileDetect. While it looks complete and seems to precisely detect a lot of device it requires to be processed on each requests (or at least at the first request).

And this is a problem. Most website have one entry point, the homepage, it is often (it is in our case), the most viewed page.

We use Varnish a lot, which provides us really good performance for no costs, and we are really happy with it. But adding a device detection to our application on the server-side would have broke our caching mechanism, and it is totally unacceptable.

As far as I know, it exists only two solutions to do device detection on the Varnish side, a WURFL VMod provided by ScientiaMobile, and the DeviceAtlas Vmod. They are both commercial solutions, and expensive ones, while they are probably worth the price, it’s still too much for us.

Basically my needs were the following: I needed to detect both the device type and the device os, at least for the four major OS on the market, iOS, Android, Blackberry, and Windows 8/Windows Phone.

I don’t need to know about device capabilities, I just need to know if it is a mobile, a tablet, or a desktop browser, and know the OS to offer our users the proper and targeted native mobile application while keeping the benefit of HTTP caching with Varnish.

So I end up writing my own. For the sake of simplicity and to save me time, I decided to go with VCL instead of diving into the abyss of the Varnish API. VCL is not C, yet it is powerful enough for this task.

The freshly written subroutine, check a bunch of common pattern in the User-Agent to detect the device and sets two pseudo variables (as part of the request object) Device-Type which can be either of mobile, tablet or generic (desktop or unkwown), and the Device-OS (known OS are iOS, Android, Blackberry, Windows 8 and Windows Phone).

The subroutine is tested against 200 User-Agent I collected from our access log and works pretty well.

Still, I plan to handle a switch option directly in Varnish by hooking a specific URL and sets a cookie to avoid redirect when the user decides to.

The project Varnish Device Detect is Github, feel free to improve or add tests.

Comments