The Fetch Event - Intercepting Network Requests
What you'll learn: How to intercept every network request your app makes and decide what to send back—the foundation of offline-first web apps.
The Power of Interception
Think of the fetch event as a security checkpoint between your web app and the internet. Every time your page requests a resource (HTML, CSS, image, API call), the service worker can intercept that request before it reaches the network. You get to decide: should I serve this from cache? Let it through to the network? Serve something completely different?
How It Works
Inside your service worker file, you listen for the fetch event. This event fires for every network request within your service worker's scope:
self.addEventListener('fetch', (event) => {
console.log('Intercepted request for:', event.request.url);
// Without intervention, request goes to network as normal
});
The event.request object contains everything about the request: URL, headers, method (GET/POST), and more.
Providing Custom Responses
The real magic happens with event.respondWith(). This method lets you hijack the request and provide your own response:
self.addEventListener('fetch', (event) => {
event.respondWith(
new Response('Hello from the service worker!', {
headers: { 'Content-Type': 'text/plain' }
})
);
});
Now every request returns your custom response instead of hitting the network. More practically, you'll use conditional logic to decide when to intercept and what to return—typically involving cache lookups you'll implement in future lessons.
Key Takeaway: The fetch event handler intercepts all network requests in your service worker's scope, and event.respondWith() lets you provide custom responses instead of the default network behavior.