Member-only story
How To Run a Proxy Server Inside Your Browser
You don’t even need a local back end — just a service worker
While I was debugging a video-chat application I was working on recently, I had to run the full chain locally. This meant running the front end locally — as well as the two REST APIs it communicates with, which are written in Java.
Now, I’m not a Java developer, so getting both APIs running on my development machine was a bit of a challenge. On top of that, I was behind a corporate proxy, and this client requires me to work on a Windows machine they provide.
I’m so lucky.
I usually work with Node.js back ends, which are much easier to run and configure, but even these can be quite cumbersome to install and run. Running a local web server to serve your front end is quite easy, but when it comes to proxying or even serving mock responses, things get complicated quickly.
So how can you run a proxy server in your browser without any back end whatsoever?
Enter service workers.
A Quiet, Underrated Revolution
For some reason, service workers never generated the amount of excitement that, for example, React and Redux did. They’re not really related, but the impact they’ve had on front-end development is profound.
Service workers are usually used in conjunction with progressive web apps and allow the interception of all network traffic to and from a website.
That means you can intercept any request your app makes and respond to it in virtually any way you want.
The main use case for a service worker is to make a website work offline, but since you can intercept network traffic, you can also use it to run a proxy server or to serve mock responses, right in your browser.
How It Works
Whenever a request is made from your website, a fetch
event will be dispatched on the service worker. Inside its event handler, you can inspect the request and take appropriate action:
self.addEventListener('fetch', e => {
console.log('request: ', e.request);
});