Skip to content

Commit de7827e

Browse files
authored
fix(service-worker): bind fetch to globalThis (#3500)
* fix(service-worker): bind fetch to `globalThis` * chore: ignore lint error
1 parent d5166dd commit de7827e

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/adapter/service-worker/handler.test.ts

+38
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,31 @@ import { Hono } from '../../hono'
22
import { handle } from './handler'
33
import type { FetchEvent } from './types'
44

5+
beforeAll(() => {
6+
// fetch errors when it's not bound to globalThis in service worker
7+
// set a fetch stub to emulate that behavior
8+
vi.stubGlobal(
9+
'fetch',
10+
function fetch(this: undefined | typeof globalThis, arg0: string | Request) {
11+
if (this !== globalThis) {
12+
const error = new Error(
13+
// eslint-disable-next-line quotes
14+
"Failed to execute 'fetch' on 'WorkerGlobalScope': Illegal invocation"
15+
)
16+
error.name = 'TypeError'
17+
throw error
18+
}
19+
if (arg0 instanceof Request && arg0.url === 'http://localhost/fallback') {
20+
return new Response('hello world')
21+
}
22+
return Response.error()
23+
}
24+
)
25+
})
26+
afterAll(() => {
27+
vi.unstubAllGlobals()
28+
})
29+
530
describe('handle', () => {
631
it('Success to fetch', async () => {
732
const app = new Hono()
@@ -20,6 +45,19 @@ describe('handle', () => {
2045
expect(json).toStrictEqual({ hello: 'world' })
2146
})
2247
it('Fallback 404', async () => {
48+
const app = new Hono()
49+
const handler = handle(app)
50+
const text = await new Promise<Response>((resolve) => {
51+
handler({
52+
request: new Request('http://localhost/fallback'),
53+
respondWith(res) {
54+
resolve(res)
55+
},
56+
} as FetchEvent)
57+
}).then((res) => res.text())
58+
expect(text).toBe('hello world')
59+
})
60+
it('Fallback 404 with explicit fetch', async () => {
2361
const app = new Hono()
2462
const handler = handle(app, {
2563
async fetch() {

src/adapter/service-worker/handler.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ export const handle = (
1616
opts: {
1717
fetch?: typeof fetch
1818
} = {
19-
// To use `fetch` on a Service Worker correctly, first refer to `self.fetch`.
20-
fetch: globalThis.self !== undefined ? globalThis.self.fetch : fetch,
19+
// To use `fetch` on a Service Worker correctly, bind it to `globalThis`.
20+
fetch: globalThis.fetch.bind(globalThis),
2121
}
2222
): Handler => {
2323
return (evt) => {

0 commit comments

Comments
 (0)