Server and Browser code are really the same. It's magic.

Overview

Service Worker Magic

  • Server (Cloudflare Workers) code is sw.js.
  • Browser ( Service Worker ) code is sw.js.
  • Cloudflare Workers sw.js serves sw.js.
  • Service Worker sw.js will be registered on /. The scope is /sw/*.
  • /server/hello => from the server.
  • /sw/hello => from the browser not from a server. Request is intercepted by Service Worker.

It's magic.

Demo

Screencast

SS

Walkthrough

Server

Run Cloudflare Workers on your terminal:

$ wrangler dev sw.js

sw.js is served by sw.js.

Browser

Access /. Your browser will load sw.js:

navigator.serviceWorker.register('/sw.js', { scope: '/sw/', type: 'module' })

Service Worker is registered.

Then...

  • /server/hello => content is returned from the server.
  • /sw/hello => content is returned from the browser. Not from the server.

Attention

If Service Worker does not work, clear the cache on your browser.

Code

Just sw.js.

Short version

It does not work well.

import { Hono } from './hono.js'
import { serveStatic } from './hono.serve-static.js'
import { logger } from './hono.logger.js'

let from = 'Service Worker'

try {
  from = FROM // "Server" is set on Cloudflare Workers environment variables
}

const app = new Hono()

// Middleware
app.use('/sw/*', logger())
app.use('/server/*', logger())
app.use('/:name{.+.js}', serveStatic({ root: './' }))


// Top page
app.get('/', (c) => {
  const html = `<html><body>
  <script>
    navigator.serviceWorker.register('/sw.js', { scope: '/sw/', type: 'module' })
  </script>
  </body></html>`
  return c.html(html)
})

// Handler
const handler = (c) => {
  const text = `Hello! from ${from}!`
  return c.text(text)
}

// Route
app.get('/server/hello', handler)
app.get('/sw/hello', handler)

// addEventListener('fetch'...
app.fire()

Related projects

sw.js is using Hono as Service Worker framework.

Author

Yusuke Wada https://github.com/yusukebe

License

MIT

You might also like...

generate statistics on the number of audience minutes your site is generating, and if readers make it to the end of your screeds

generate statistics on the number of audience minutes your site is generating, and if readers make it to the end of your screeds

audience-minutes generate statistics on the number of audience minutes your site is receiving, and if readers make it to the end of your screeds. “If

Dec 28, 2022

Challenge [Frontend Mentor] - In this challenge, JavaScript was used to filter jobs based on the selected categories. Technologies used: HTML5, CSS3 and React.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Apr 13, 2022

A simple package for single or batch image download and conversion using node streams.

image-batch-download A simple package for basic image downloading and processing. Supported formats: JPEG PNG WebP Installation With Yarn: yarn add im

Jan 2, 2022

A general-purpose message and event queuing library for MongoDB

MongoMQ2 MongoMQ2 is a light-weight Node.js library that turns MongoDB collections into general-purpose message queues or event logs, without addition

Dec 28, 2022

A simple Node.js APIBAN client for downloading banned IPs and inserting them into a redis set

apiban-redis A simple Node.js APIBAN client for downloading banned IPs and inserting them into a redis set. Installation This utility can be run as a

Apr 5, 2022

Out of the box modern User Interface, so you can see and manage your Workhorse jobs in realtime

Out of the box modern User Interface, so you can see and manage your Workhorse jobs in realtime

WORKHORSE UI Out of the box modern User Interface, so you can see and manage your Workhorse jobs in realtime. Start local Run npm i Copy and name prox

Apr 15, 2022

Store and Deliver images with R2 backend Cloudflare Workers.

Store and Deliver images with R2 backend Cloudflare Workers.

r2-image-worker Store and Deliver images with Cloudflare R2 backend Cloudflare Workers. Synopsis Deploy r2-image-worker to Cloudflare Make a base64 st

Jan 3, 2023

Opinionated, type-safe, zero-dependency max/min priority queue for JavaScript and TypeScript projects.

qewe qewe is an opinionated, type-safe, zero-dependency max/min priority queue for JavaScript and TypeScript projects. Installation Add qewe to your p

Jan 10, 2022

Cache is easy to use data caching Node.js package. It supports Memcached, Redis, and In-Memory caching engines.

Cache Cache NPM implements wrapper over multiple caching engines - Memcached, Redis and In-memory (use with single threaded process in development mod

Oct 24, 2022
Self-hosting web code editor (for Hack Club CodeJelly)

reflection Self-hosting web code editor (for Hack Club CodeJelly) Reflection-editor is a code editor that edits its own code, and uses modern web tech

Benjamin Smith 7 Dec 29, 2021
Job queues and scheduled jobs for Node.js, Beanstalkd and/or Iron.io.

Ironium Job queues and scheduled jobs for Node.js backed by Beanstalk/IronMQ/SQS. The Why You've got a workload that runs outside the Web app's reques

Assaf Arkin 71 Dec 14, 2022
Bree is the best job scheduler for Node.js and JavaScript with cron, dates, ms, later, and human-friendly support.

The best job scheduler for Node.js and JavaScript with cron, dates, ms, later, and human-friendly support. Works in Node v10+ and browsers, uses workers to spawn sandboxed processes, and supports async/await, retries, throttling, concurrency, and graceful shutdown. Simple, fast, and lightweight. Made for @ForwardEmail and @ladjs.

Bree - The Best Node.js and JavaScript Job Scheduler 2.5k Dec 30, 2022
Type-safe and Promisified API for Web Worker and Iframe

?? You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. typed-worker Install npm i typed-worker Usage Create

EGOIST 189 Dec 31, 2022
Premium Queue package for handling distributed jobs and messages in NodeJS.

The fastest, most reliable, Redis-based queue for Node. Carefully written for rock solid stability and atomicity. Sponsors · Features · UIs · Install

null 13.5k Dec 31, 2022
Redis-backed task queue engine with advanced task control and eventual consistency

idoit Redis-backed task queue engine with advanced task control and eventual consistency. Task grouping, chaining, iterators for huge ranges. Postpone

Nodeca 65 Dec 15, 2022
A fast, robust and extensible distributed task/job queue for Node.js, powered by Redis.

Conveyor MQ A fast, robust and extensible distributed task/job queue for Node.js, powered by Redis. Introduction Conveyor MQ is a general purpose, dis

Conveyor MQ 45 Dec 15, 2022
Build and deploy a roadmap voting app for your porject

Roadmap Voting App You can deploy Roadmap application yourself and get feedback from your users about your roadmap features. See the live example. In

Upstash 91 Jan 3, 2023
Making service workers easy so that your app is fast and reliable, even offline.

tulo.js Making service workers easy to use so that your app can be fast and reliable, even offline. Welcome to tulo.js, a service worker library that

OSLabs Beta 37 Nov 16, 2022
Example repo for getting NextJS, Rust via wasm-pack, and web workers all playing nicely together.

Example of integrating WASM & web workers with a Typescript NextJS project. Running yarn yarn dev Open localhost:3000 Layout Rust code is in ./rust, g

Studio Lagier 63 Dec 23, 2022