GitHub iconEdit on GitHub

fetch()

Overview

The Fetch API provides an interface for asynchronously fetching resources via HTTP requests inside of a Worker.

Global

The fetch method is implemented on the ServiceWorkerGlobalScope. See MDN documentation for more information.

Note: Asynchronous tasks such as fetch are not executed at the top level in a Worker script and must be executed within a FetchEvent handler such as respondWith. Learn more about Request Contexts.

Syntax

fetch(request: Request| string, init?:RequestInit) : Promise<Response>

request: A Request object or a string representing the URL to be fetched.

Usage

addEventListener('fetch', (event) => {
  // NOTE: don’t use fetch here, as we're not in an async scope yet
  event.respondWith(eventHandler(event))
})
async function eventHandler(event) {
  // fetch can be awaited here since `event.respondWith()` waits for the Promise it receives to settle
  const resp = await fetch(event.request)
  return resp
}

Examples