So I've been struggling to register a Service Worker on localhost to test its functionality while developing a website. According to the MDN guide for service workers, it states that the code for service workers can only be registered on HTTPS connections, but also considered localhost a secure origin for local development [https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#setting_up_to_play_with_service_workers]. However, when I attempt to register it, I get the error
DOMException: The operation is insecure. main.min.js:1:310
<anonymous> http://localhost:3000/js/main.min.js:1
I then tried to HTTPS my localhost connection with a cert made from mkcert and applied the cert with a nginx reverse proxy. After getting that setup I got https://localhost:8080/ to work and serve the website, but I still get the above error, but with https://localhost:8080/js/main.min.js:1 listed instead.
So now I'm out of ideas on how to get this registration to work for local development. I am on FireFox if that adds any extra help.
Server Worker Registration Code:
if ('serviceWorker' in navigator)
try {
const registration = await navigator.serviceWorker.register('/js/serviceWorker.min.js', { scope: '/' })
if (registration.installing)
console.log('Service Worker is installing')
else if (registration.waiting)
console.log('Service Worker is installed and waiting')
else if (registration.active)
console.log('Service Worker is active')
}
catch (error) {
console.error(error)
}
else
console.log('Service Workers are not supported here. :(')
Nginx Config:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8080 ssl;
server_name localhost;
ssl_certificate /Users/soul/localhost.pem;
ssl_certificate_key /Users/soul/localhost-key.pem;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Accept-Encoding "";
proxy_pass http://localhost:3000;
}
}
}
I figured out what I was doing wrong after testing out the problem in another browser, Safari, as they gave me a better error message. In my registeration code I was doing { scope: '/' }, but since the file was coming from /js it wasn't working. Removing that arugment from the .register method made it work! And I didn't need to https my localhost.
// Failed
const registration = await navigator.serviceWorker.register('/js/serviceWorker.min.js', { scope: '/' })
// Worked
const registration = await navigator.serviceWorker.register('/js/serviceWorker.min.js')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With