Respond with another site
Answer a request with content fetched from another site, relaying the upstream response while the browser keeps the original URL.
Answer an incoming request with content fetched from a different website. Use this pattern for a temporary substitution, or to serve another site’s response without issuing an HTTP redirect that changes the URL in the browser.
How it works
The function listens for the fetch event with addEventListener. Instead of building a local Response, it calls fetch() to request a resource from another site and passes the resulting promise straight to event.respondWith(), which accepts a promise as well as a Response. The function waits for the upstream response and relays it back to the client as the answer to the original request.
The substitution happens inside the function, so the visitor’s address bar keeps the original URL. The outbound fetch() counts against the sub-request limit for the invocation, and the upstream site’s status and headers are the ones the client receives.
The relayed response can be kept rather than fetched again on the next request. The Cache API writes it with cache.put(request, fetchResponse.clone()), and handing that call to ctx.waitUntil() keeps the write off the response path.