Random ramblings of a anonymous software engineer. Contains occasional profanity. Personal opinions, not related to employer.

Local Debugging of Service Workers

Service workers requires a secure origin to work. For this reason, to debug service workers locally you will need to setup a HTTPS server on your local machine - unfortunately it isn't an entirely straightforward process. Here is a quick and dirty trick to do this.

First, you will need to create a self signed certificate. This can be done using the following command. (Example is valid for 10 years, Do not do this in production. Bad idea.)

openssl req -new -x509 -keyout /usr/local/etc/local-server.pem -out /usr/local/etc/local-server.pem -days 3650 -nodes

Then. you will need to start a local server that uses this certificate and serves HTTPS. The following snippet should be placed in a convenient location for execution, in my case I put it in /usr/local/bin/https-server. Put it wherever works for you, and add a +x bit. This is for Python 2.7. (or near versions.)

import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='/usr/local/etc/local-server.pem', server_side=True)

(Note: The HTTP server modules have been moved in Python 3.x, so that will need to be patched.)

Now, go to the directory where you have the SW based application running. For the example of our JavaScript SDK, this will be the root of the checked out repository. Run the https-server script. If you prefer a standard port, you will need to change the line that mentioned 4443 above to 443, and run the server as root. This is not recommended.

The following example only covers Chrome. Other implementations probably involve different tricks for working around certificate validation.

Close all instances of Chrome. (or whatever Chrome based browser you are running) Make sure the root process is completely dead, and not just all the tabs closed. Now, start Chrome with the following flags:

--ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://localhost:4443

On macOS, this would normally be:

/Applications/Google\\ Chrome  --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://localhost:4443

On Linux, this would normally be:

google-chrome  --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=https://localhost:4443

Now, you can go to https://localhost:4443 and debug your service worker locally. When you are done, make sure you shutdown the current browser instance - as the flag overrides are not safe for everyday browsing.