Skip to main content

Strategy

First added

Workbox

About

Abstract class for implementing runtime caching strategies.

Custom strategies should extend this class and leverage StrategyHandler, which will ensure all relevant cache options, fetch options, and plugins are used (per the current strategy instance), to perform all fetching and caching logic.

Abstract methods

  • _handle(request, handler) — The main handling logic of the strategy. It is provided with two parameters:
    • request — The Request the strategy should return a response for.
    • handler — The StrategyHandler instance automatically created for the current strategy.

Methods and fields

  • handle(options) — Performs a request strategy and returns a Promise that will resolve with a Response, invoking all relevant plugin callbacks. When a strategy instance is registered with a Route, this method is automatically called when the route matches. Alternatively, this method can be used in a standalone FetchEvent listener by passing it to event.respondWith().
  • handleAll(options) — Similar to handle(), but instead of just returning a Promise that resolves to a Response, it will return an tuple of [response, done] promises, where response is equivalent to what handle() returns, and done is a Promise that will resolve once all promises added to event.waitUntil() as a part of performing the strategy have completed. You can await the done promise to ensure any extra work performed by the strategy (usually caching responses) completes successfully.

Usage

import { Strategy, type StrategyHandler } from "serwist";

class NetworkOnly extends Strategy {
  _handle(request: Request, handler: StrategyHandler) {
    return handler.fetch(request);
  }
}

More resources

Here is a list of resources you can read to learn more about Strategy: