Skip to content

IFetchInterceptor

David Ortner edited this page Jan 20, 2025 · 5 revisions

IFetchInterceptor represents a fetch interceptor containing hooks that are dispatched before and after making requests. It is used to intercept requests and responses and modify them.

Signature

interface IFetchInterceptor

Properties

Property Type Default Description
beforeAsyncRequest? (context: { request: Request; window: BrowserWindow; }) => Promise<Response | void> Hook that is dispatched before making an async request. Return a Response object to use it instead of performing the fetch.
beforeSyncRequest? (context: { request: Request; window: BrowserWindow; }) => ISyncResponse | void Hook that is dispatched before making an async request. Return an object following the ISyncResponse interface to use it instead of performing the fetch.
afterAsyncResponse? (context: { request: Request; response: Response; window: BrowserWindow; }) => Promise<Response | void> Hook that is dispatched after receiving the response for an async request.
afterSyncResponse? (context: { request: Request; response: ISyncResponse; window: BrowserWindow; }) => ISyncResponse | void Hook that is dispatched after receiving the response for a sync request.

Example

import { Window, ISyncResponse } from "happy-dom";

const window = new Window({
   settings: {
      fetch: : {
         interceptor: {
            beforeAsyncRequest: async ({ request, window }) => {
               if (request.url === "https://example.com") {
                  return new window.Response("Hello World");
               }
            },
            beforeSyncRequest: ({ request, window }) => {
               if (request.url === "https://example.com") {
                  return <ISyncResponse>{
                     status: 200,
                     statusText: "OK",
                     ok: true,
                     url: "https://example.com",
                     redirected: false,
                     headers: new window.Headers(),
                     body: Buffer.from("Hello World"),
                  };
               }
            },
            afterAsyncResponse: async ({ request, response, window }) => {
               if (request.url === "https://example.com") {
                  return new window.Response("Hello World");
               }
            },
            afterSyncResponse: async ({ request, response, window }) => {
               if (request.url === "https://example.com") {
                  return <ISyncResponse>{
                     status: 200,
                     statusText: "OK",
                     ok: true,
                     url: "https://example.com",
                     redirected: false,
                     headers: new window.Headers(),
                     body: Buffer.from("Hello World"),
                  };
               }
            },
         }
      }
   }
});
Clone this wiki locally