Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: general
fetchnetworkperformanceasyncerror-handling

Enforce timeouts on network requests

Always attach an AbortController signal to fetch requests to prevent indefinite hanging on slow networks.

PR: Feat/FCK-1669 - Adding Job Landing Page #3656Created: Dec 8, 2025

Bad example

Old codets
1const fetchData = async () => {
2 try {
3 // BAD: No timeout configured.
4 // If the API hangs, this promise remains pending indefinitely.
5 const res = await fetch('https://api.example.com/items');
6 const data = await res.json();
7 setData(data);
8 } catch (error) {
9 console.error(error);
10 }
11};

Explanation (EN)

The fetch request lacks a timeout mechanism. If the server hangs or the connection drops silently, the application will wait indefinitely, leading to frozen UI states and resource exhaustion.

Objašnjenje (HR)

Fetch zahtjev nema mehanizam za prekid (timeout). Ako server zastane ili veza pukne, aplikacija će čekati u nedogled, što dovodi do smrznutog sučelja i trošenja resursa.

Good example

New codets
1const fetchData = async () => {
2 const controller = new AbortController();
3 // Set a 5-second timeout
4 const timeoutId = setTimeout(() => controller.abort(), 5000);
5
6 try {
7 const res = await fetch('https://api.example.com/items', {
8 signal: controller.signal
9 });
10 const data = await res.json();
11 setData(data);
12 } catch (error) {
13 if (error.name === 'AbortError') {
14 console.error('Request timed out');
15 } else {
16 console.error('Fetch error:', error);
17 }
18 } finally {
19 // Always clear the timer to prevent memory leaks
20 clearTimeout(timeoutId);
21 }
22};

Explanation (EN)

An AbortController is used to explicitly cancel the request if it exceeds the defined timeout. The logic handles the specific 'AbortError' and ensures the timer is cleared in the 'finally' block.

Objašnjenje (HR)

AbortController se koristi za eksplicitno otkazivanje zahtjeva ako pređe definirani limit. Logika obrađuje specifičnu 'AbortError' grešku i osigurava da se timer očisti u 'finally' bloku.