mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
537 stars 123 forks source link

Intercepting all requests #138

Closed JohnPhamous closed 3 years ago

JohnPhamous commented 3 years ago

Hello,

I'm trying to intercept all network requests on a web app. I'd like to record everything that shows up in the Networks tab in the browser developer tools (except for web sockets).

I've added interceptors to my web app:

const interceptor = createInterceptor({
    modules: browserInterceptors,
    resolver(req, ref) {
        console.log(req.url);

        console.log(ref);
    },
});

interceptor.apply();

I have 2 buttons that make requests:

<button
    onClick={async () => {
        const data = await fetch(
            'https://pokeapi.co/api/v2/pokemon/1'
        );
        const json = await data.json();
        console.info({ json });
    }}
>
    Fetch Request
</button>
<button
    onClick={async () => {
        const oReq = new XMLHttpRequest();
        oReq.open('GET', 'https://pokeapi.co/api/v2/pokemon/1');
        oReq.send();
    }}
>
    XHR
</button>

Problems

  1. The XHR request interceptor is working. The fetch isn't. I'm getting this error for fetch: TypeError: Failed to execute 'json' on 'Response': body stream already read
    • Looks like #113 is related?
  2. Other network requests that are not using XHR are not being intercepted (should they?).

Things I've checked

  1. Using the browserInteceptors module, fetch and XMLHttpRequest are being shimmed. I checked this by running fetch and XMLHttpRequest in the console and the output was not XMLHttpRequest() { [native code] }.
kettanaito commented 3 years ago

Hey, @JohnPhamous.

I highly recommend using MSW for request interception in both browser and Node.js. MSW uses Service Worker API that intercepts requests regardless of the request client in the browser, so that would be an ideal solution for your monitoring tool.

The "interceptors" library is a backbone for the Node.js support in MSW and although it can be used standalone, MSW provides a much better experience in a browser due to the usage of the Service Worker.

You can follow this step-by-step tutorial to set up the requests interception in the browser.


That being said, the "body stream already read" issue does seem related to #113. It looks like we need to clone the response before reading its body. Please, would you be interested in providing a pull request to fix that?

Other network requests that are not using XHR are not being intercepted (should they?).

What kind of network requests are you referring to? Can you give an example?

Overall, the in-browser interception in this library is achieved by request client stubbing and concerns only the requests made via window.fetch or XMLHttpRequest.

kettanaito commented 3 years ago

Should be fixed in #152. Please try this out in the next release.