Testing on Devices Using a Local Webserver

Although it's improved in recent times, one of the painful aspects of web development can be testing that your site works well on mobile devices.

This particularly applies when you're developing on your local laptop with wireless network connection, and want to view the site on a mobile device, without first having to deploy to a staging server.

Ngrok

One tool that takes much of this pain away is ngrok, which is described on the site thusly:

“I want to securely expose a local web server to the internet and capture all traffic for detailed inspection and replay.”

ngrok creates a tunnel from the public internet (http://subdomain.ngrok.com) to a port on your local machine. You can give this URL to anyone to allow them to try out a web site you're developing without doing any deployment.

What this means is that, when we're webserving a site such as http://mebooks.localhost on our laptop, within a couple of minutes we can be visiting a URL such as http://mebooks.ngrok.com in a mobile browser and seeing the same site; as long as the mobile browser has a connection to the internet, it should be able to load our page.

Configuration

The subdomain assigned by ngrok is not guaranteed to last from one session to the next, so ideally we want to use a custom subdomain such as mebooks.ngrok.com.

We can easily specify a custom subdomain when starting ngrok:

./ngrok -subdomain mebooks 80

However, while we don't have to pay to be able to use a custom domain, unless we've paid a donation to ngrok these subdomains are on a first-come basis; if someone else has paid to reserve our subdomain or is currently using ngrok with the specified subdomain, then we won't be able to use it.

Once logged in, we'll find a auth token on our dashboard that allows us to identify ourselves. This auth token only needs to be specified once, as it then gets saved in ~/.ngrok.

Typically, on our local webserver we'll be serving our site using a name-based virtual host, expecting to see our site at http://mebooks.localhost, and having the following in our /etc/private/hosts file:

127.0.0.1 mebooks.localhost

To ensure that our webserver can correctly capture requests from http://mebooks.ngrok.com, we need to ensure that our vhost has the ServerAlias mebooks.ngrok.com set, and our webserver has been restarted.