Sunday, November 3, 2013

Mobile Device Detection and Redirection in Node+Express

One of the challenges of writing a mobile web site is what to do if a user hits the site from a desktop? Of course, some will say that you should simply make the site responsive, able to look good regardless of the browse it is displayed on. But what if the site is a game? I know all of the responsive design true believers will be upset with my solution, but so what, I like it. I "iframe" the mobile site into a 320 x 480 window on the desktop page. This brings up more challenges, like how detect a mobile device and how to route to the correct page?

The first challenge has already been solved by the excellent web site: They have created a rather long regular expressions which detects a mobile browser by its user agent. The answer to the second challenge comes from the Express.js middleware which makes Node.js a great framework. 

Express allows the developer to inject middleware into the route handler. For our root route we will call the checkForMobile method. If we detect a mobile browser, we will redirect to our mobile route. On all other routes, we won't bother checking for mobile. If a desktop user wishes to navigate directly to the mobile page, we will let them.

Please check out the code sample below to see how it is done. Or if your are interested in the complete, and still in progress, mobile game check it out at: To see the live and very much in progress code, go to:

I will be talking about the complete game at So Cal Code Camp at USC, the weekend of November 9th & 10th. If you are in the area, be sure to attend. It is a free event: