Search code examples
javascripthttpbrowserfetchhttp2

Reuse http connection with backend server - web fetch API


I host my website on example.com I host my graphQL backend on graphql.example.com which serves JSON over CORS. As I understand it, every request to window.fetch('https://graphql.example.com/', ...) requires creating a new connection. I know that the browser is able to reuse the same connection for multiple assets made to example.com via http2. For example, if my webpage has the <img>s example.com/a.jpg and example.com/b.jpg I only have to pay setting up the cost of the connection once.

Is there anyway to reuse the connection in a similar way

  • (a) with window.fetch()
  • (b) to another domain requiring CORS

Solution

  • I was wrong about this. All fetch requests to graphql.example.com over CORS can reuse the same tcp connection. You can check this by running this example and checking the Connection ID in chrome dev tools enter image description here.

    CORS requests will however use a different connection to non-CORS requests to the same server.

    For example say you request example.com/a.jpg and example.com/b.jpg via an image tag, they will be served without CORS over one connection.

    All CORS requests to fetch('graphql.example.com') will be served over a different connection.