Skip to content

Allow using fetch with agent to reuse connections in server hooks #7391

@orenwang

Description

@orenwang

Describe the problem

In the docs for handleFetch hook it recommends to hit the API directly during SSR, which I agree:

export async function handleFetch({ request, fetch }) {
  if (request.url.startsWith('https://api.yourapp.com/')) {
    // clone the original request, but change the URL
    request = new Request(
      request.url.replace('https://api.yourapp.com/', 'http://123.123.123.123:9999/'),
      request
    );
  }
 
  return fetch(request);
}

However, if we could reuse TCP connections, this could be a lot faster than reestablishing every TCP connection like above. This is especially important if anyone, like me, wants to act like a proxy inside handle hook to avoid any CORS requests to an API. Currently we cannot reuse TCP connections with fetch because there is no such agent option we can pass, as specified in node-fetch docs, making every request way too slow.

Describe the proposed solution

Because handle and handleFetch are both server hooks, I assume the fetch we are using here is node-fetch, right? So we should be able to do something like this:

import http from 'node:http';

const httpAgent = new http.Agent({
	keepAlive: true
});

export async function handleFetch({ request, fetch }) {
  if (request.url.startsWith('https://api.yourapp.com/')) {
    // clone the original request, but change the URL
    request = new Request(
      request.url.replace('https://api.yourapp.com/', 'http://123.123.123.123:9999/'),
      request
    );
  }
 
  return fetch(request, {agent: httpAgent});
}

Alternatives considered

No response

Importance

i cannot use SvelteKit without it

Additional Information

I have tried to use fetch with keepalive option, but it does not have any effect. Plus, I don't feel this keepalive option is a "server-side" thing:

fetch(request, {keepalive: true});

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions