Course contentsShow
← Security
Lesson 1081 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Service Worker Security Model and Origins

Understanding service worker lifecycle, scope restrictions, and how origin-based isolation protects against unauthorized control.

Service Worker Security Model and Origins

You'll learn how service workers are isolated, scoped, and tied to origins to prevent malicious scripts from hijacking your entire browsing experience.


What Are Service Workers and Why They're Powerful

Service workers are JavaScript files that run in the background, intercepting network requests for a website. Think of them as a security guard at a building entrance — they can inspect, block, or modify every request going in or out. This power makes them incredibly useful for offline features and caching, but also dangerous if misused.


Origin-Based Isolation

Service workers strictly follow the Same-Origin Policy you've already learned. A service worker registered on https://example.com cannot intercept requests from https://evil.com or even http://example.com (different scheme). This prevents cross-site hijacking.

Key rule: Service workers can only control pages from the exact same origin (scheme + host + port).


Scope Restrictions

Each service worker has a scope — the directory path it can control. If registered at /app/sw.js, it can only intercept requests starting with /app/. It cannot control /admin/ or the root / unless explicitly registered there.

Analogy: A security guard for the third floor cannot access the lobby or basement without separate authorization.

This prevents a compromised or malicious script in one part of your app from controlling the entire site.


Lifecycle and HTTPS Requirement

Service workers must be served over HTTPS (except localhost for development). This prevents man-in-the-middle attackers from injecting malicious service workers during registration.

Their lifecycle (install → activate → control) ensures updates are atomic and predictable, reducing race conditions that could be exploited.


Key Takeaway:
Service workers are isolated by origin and scope, must use HTTPS, and follow strict lifecycle rules to prevent unauthorized control over network traffic and page behavior.