How Do I Adjust the Timeout for Fetch API POST Requests?

I am utilizing the fetch method to execute a POST request and include credentials. Below is an example of my implementation:

async function sendData(apiEndpoint, dataPackage) {
    const result = await fetch(apiEndpoint, {
        method: 'POST',
        body: dataPackage,
        credentials: 'include'
    });
    return result.json();
}

I am trying to figure out what timeout is applied automatically when using this fetch request. Additionally, I would like to know how to change this setting to enforce a timeout of 3 seconds or even keep it waiting indefinitely. Any guidance or suggestions on configuring the request timeout would be very helpful.

In my experience working with fetch, I discovered that it does not include any built-in timeout. When dealing with uncertain server response times, I applied the AbortController to impose a timeout by scheduling an abort after three seconds using a timer. This was crucial in avoiding hanging requests, particularly when response times were unpredictable. In cases where an indefinite wait is necessary, I simply refrained from triggering the abort logic. Using this technique provided me with full control over when requests should be cancelled or left pending.

ya, fetch doesnt auto apply a timeout. use abortcontroller with setTimeout to cancel the request after 3 secs if needed. no easy way to keep it waiting indefinately either, you’ll just need to handle your abort logic

hey, i used abortcontrller in a project to manage fetch timeouts. just set a settimeout for 3000ms to fire abort and if u dont need a timeout, simply skip it. hope it helps, cheers

During my last project, I faced a similar challenge. I learned that the fetch API does not automatically apply any timeout mechanism, which can lead to hanging requests if the server doesn’t respond. My solution was to integrate an AbortController that could be activated after a given period, such as 3 seconds, using a simple timer. Adjusting the delay was as straightforward as changing the timer value. If you require an indefinite wait, then avoid invoking the abort function. This approach gave me precise control over request behavior.

In my projects, I encountered similar challenges with fetch as many have noted that it doesn’t have a built-in timeout. I found that using AbortController offers a flexible way to cancel a request after a desired period by manually triggering an abort via a timer. By incorporating this approach, you can set your fetch request to default to cancel after 3 seconds, or allow it to run indefinitely if the abort signal isn’t triggered. This extra layer of control has proven valuable in handling varying server response times and makes error handling considerably easier.