Service Workers: How to Run a Man-in-the-middle Attack on Your Own Site for Fun and Profit

Rate this content
Bookmark
Service workers can enhance web performance and resilience by caching assets for offline access and intercepting network requests. They enable fast page loads, reduced API calls, and improved user experience. By using service workers, developers can cache JSON responses and serve them instantly, providing a more resilient experience. Service workers can also modify API requests, acting like a man-in-the-middle attack on your own site. For example, they can intercept GET requests and change search parameters. Offline-first and network-first strategies are used to manage caching and network requests. Service workers require SSL certificates to function correctly and can be integrated gradually into existing code bases. Static site generators and CDNs can be paired with service workers for faster performance. Service workers are valuable for caching assets, providing offline access, and improving overall web performance.

From Author:

Service workers bring amazing new capabilities to the web. They make fully offline web apps possible, improve performance, and bring more resilience and stability to any site. In this talk, you'll learn how these man-in-the-middle attacks on your own site work, different approaches you can use, and how they might replace many of our current best practices.

This talk has been presented at JSNation Live 2021, check out the latest edition of this JavaScript Conference.

FAQ

A service worker is a JavaScript file that your website installs into the browser, acting as an intermediary between the browser and the network. It intercepts requests and responses, allowing operations like caching assets for offline use, enhancing performance and reliability.

To install a service worker, you first check if the navigator object supports service workers. If supported, use the register method to register the service worker JavaScript file. This file is then downloaded asynchronously, and on subsequent visits, it intercepts network requests and responses.

The two basic strategies for implementing service workers are 'network first' and 'offline first'. Network first checks the network for data before using cache, while offline first checks the cache before reaching out to the network. Each strategy suits different types of assets and user experience needs.

Caching in service workers allows web applications to store assets like HTML, CSS, JavaScript, and images locally in the browser. This enables faster load times and offline functionality, as assets can be retrieved from the cache instead of the network, reducing dependency on internet connectivity.

Service workers require an SSL certificate to operate, ensuring secure data transmission. However, for locally hosted sites used for testing purposes on your own machine, an SSL certificate is not necessary.

Service workers are used for caching assets for performance improvement, providing offline access to cached content, preloading critical assets, and enhancing web applications' resilience by serving fallback content when online resources are unavailable.

Unlike traditional caching, which often only caches static resources, service workers allow dynamic control over the caching process, including the ability to intercept and manage requests and responses in real-time, cache more types of content, and provide sophisticated offline functionalities.

Service workers enhance performance by intercepting network requests and serving cached assets instead of fetching them from the server. This reduces load times, saves bandwidth, and provides a smoother user experience, especially in conditions of poor connectivity.

Yes, service workers primarily handle 'GET' requests and cannot intercept 'POST', 'PUT', or 'DELETE' requests. They also require careful management of cache to avoid serving outdated content and must be updated and managed to ensure they function as intended.

Chris Ferdinandi
Chris Ferdinandi
34 min
09 Jun, 2021

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to Service Workers

Short description:

Welcome to Service Workers. JavaScript is unreliable and easily broken. Bandwidth has increased, but the web is not faster due to larger websites. Service workers provide resilience and make sites faster.

Welcome to Service Workers, or How to Run a Man-In-the-Middle Attack on Your Own Site for Fun and Profit. We, and by we I mean web developers, have broken the web. We've built the front end around JavaScript, which is a fragile house of cards. It's unreliable and easily broken, as anyone who's ever run into a blank web page or a button that does nothing when clicked can easily attest to.

All of this JavaScript has big performance implications as well. Bandwidth has gone way up in the last five years. It's actually about three times faster on average on both mobile and desktop than it was in 2017. But because websites have gotten bigger as well and because so much of the front end is rendered in the browser with JavaScript now, the web isn't actually meaningfully faster than it was five years ago. And the problem with averages is that some countries have internet that's actually up to six times faster than five years ago, but many countries continue to struggle with desktop speeds that are slower than the average mobile speed was five years ago. Bandwidth is not evenly distributed and as is often the case, people who live in poverty tend to suffer the most.

So what I wanna talk to you about today are service workers. A newer-ish tool in our toolkit that we can use to provide more resilience in the things that we build. Service workers can make our sites faster and allow us to build websites and apps that continue to function even when things go wrong.

2. Service Workers: Strategies and Examples

Short description:

Hi, I'm Chris Ferdinandi, the Vanilla JS guy. Service workers are JavaScript files that sit between the browser and the network. They intercept requests and responses, providing a storage mechanism with a cache. They can save copies of responses and load assets from the cache if the network fails. Service workers require encryption and SSL certificates.

Hi, I'm Chris Ferdinandi, that's my face. You can find me online at gomakethings.com. I'm known on the internet as the Vanilla JS guy. I teach people JavaScript and ironically, spend a lot of my time telling people how to use less of it in the things that we build. I write a free daily newsletter and create courses and run workshops and you can find more info about all that at gomakethings.com.

Here's the agenda for today's talk. We're gonna spend a bunch of time talking about what service workers are and how they work and then we're gonna dig into some specific strategies you can use when implementing them. Finally, we'll take a look at some cool things that you can do with them. I always find that looking at specific tangible examples helps make this stick. We are going to look at code, but we only have about 18 minutes left and you can easily fill an hour-long talk with just code examples, so we're gonna stick to some pretty high-level surface examples.

So, what is a service worker? Whenever a browser accesses a website or web app that you've built, it reaches out to the network and it gets a bunch of assets back. HTML, CSS, JavaScript, images, fonts. A service worker is a JavaScript file that your website installs into the browser that sits between the browser and the network. And to do that, wherever you would normally load the rest of your JavaScript, you write a little bit of JS. You check to see that the navigator object exists and that it has the service worker property, because older browsers don't support this. And if it does, you can use the register method to register a service worker, which is just a JavaScript file. And then in the background, the browser will download that file asynchronously. And the next time a user visits your website, it will install it and activate it. And once it does, your service worker intercepts all requests that go out to the network and all responses that come back from it. And because a service worker is a JavaScript file, we can do that with a fetch event listener, just using the add event listener method. And we can do things with those requests and responses.

What makes service workers really powerful is that they have a built-in storage mechanism. They have a cache and it can hold a lot of stuff, way more than local storage or cookies can. And you can actually take those responses that come back, save copies of them in your cache. And if something goes wrong with the network, you can load assets from your locally saved cache instead of the network, or cut it out altogether if you want. A service worker is a man-in-the-middle attack on your own website, but like a good one. Now obviously there's a lot of potential for abuse with something like this. So service workers require browser encryption and SSL certificate to work. There's an exception to this made for locally hosted sites. So if you're just running it on your laptop to test it, you don't need a certificate for that.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
PlayCanvas is an open-source game engine used by game developers worldwide. Optimization is crucial for HTML5 games, focusing on load times and frame rate. Texture and mesh optimization can significantly reduce download sizes. GLTF and GLB formats offer smaller file sizes and faster parsing times. Compressing game resources and using efficient file formats can improve load times. Framerate optimization and resolution scaling are important for better performance. Managing draw calls and using batching techniques can optimize performance. Browser DevTools, such as Chrome and Firefox, are useful for debugging and profiling. Detecting device performance and optimizing based on specific devices can improve game performance. Apple is making progress with WebGPU implementation. HTML5 games can be shipped to the App Store using Cordova.
Power Fixing React Performance Woes
React Advanced Conference 2023React Advanced Conference 2023
22 min
Power Fixing React Performance Woes
Top Content
Watch video: Power Fixing React Performance Woes
This Talk discusses various strategies to improve React performance, including lazy loading iframes, analyzing and optimizing bundles, fixing barrel exports and tree shaking, removing dead code, and caching expensive computations. The speaker shares their experience in identifying and addressing performance issues in a real-world application. They also highlight the importance of regularly auditing webpack and bundle analyzers, using tools like Knip to find unused code, and contributing improvements to open source libraries.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Performance Debugging
React Advanced Conference 2023React Advanced Conference 2023
148 min
React Performance Debugging
Workshop
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
High-performance Next.js
React Summit 2022React Summit 2022
50 min
High-performance Next.js
Workshop
Michele Riva
Michele Riva
Next.js is a compelling framework that makes many tasks effortless by providing many out-of-the-box solutions. But as soon as our app needs to scale, it is essential to maintain high performance without compromising maintenance and server costs. In this workshop, we will see how to analyze Next.js performances, resources usage, how to scale it, and how to make the right decisions while writing the application architecture.
Maximize App Performance by Optimizing Web Fonts
Vue.js London 2023Vue.js London 2023
49 min
Maximize App Performance by Optimizing Web Fonts
WorkshopFree
Lazar Nikolov
Lazar Nikolov
You've just landed on a web page and you try to click a certain element, but just before you do, an ad loads on top of it and you end up clicking that thing instead.
That…that’s a layout shift. Everyone, developers and users alike, know that layout shifts are bad. And the later they happen, the more disruptive they are to users. In this workshop we're going to look into how web fonts cause layout shifts and explore a few strategies of loading web fonts without causing big layout shifts.
Table of Contents:What’s CLS and how it’s calculated?How fonts can cause CLS?Font loading strategies for minimizing CLSRecap and conclusion