Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › AWS API Gateway

How to Fix WebSocket Timeout in JavaScript: Handshake, Idle, Proxy, and Reconnect Solutions

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A WebSocket timeout is not one error. Find the phase that fails—handshake, backend integration, idle connection, or unexpected network closure—then fix the component that owns that phase. In browser JavaScript, use an application heartbeat and acknowledgment because the native WebSocket API has no ping() method. Keep the heartbeat interval below the shortest idle timeout on the complete client-to-server path, and reconnect with bounded backoff when a connection ends.

A direct localhost test can appear healthy while a deployed socket is closed by a TLS terminator, reverse proxy, load balancer, NAT, firewall, or managed gateway. The steps below show how to identify that hop, separate AWS API Gateway’s limits when applicable, and build a client that detects failure and recovers without creating a reconnect storm.

As an Amazon Associate I earn from qualifying purchases.

Identify which WebSocket phase is timing out

Start by naming the failing phase. The remedy for a failed HTTP upgrade is different from the remedy for a socket that works for several minutes and then disappears.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handshake failure

The browser has not established a WebSocket yet. In DevTools, the request never reaches an open state, the response is not a successful WebSocket upgrade, or the browser reports a connection error immediately. Typical causes include a wrong ws:// or wss:// URL, an incorrect port or path, failed authentication, a certificate problem, a redirect, or a proxy that does not forward the upgrade request.

#1 Best Overall
Sale
TP-Link AX1800 WiFi 6 Router (Archer AX21 V5) | Dual Band Wireless Internet, Gigabit, Easy Mesh, Works with Alexa - A Certified for Humans Device
  • DUAL-BAND WIFI 6 ROUTER: Wi-Fi 6(802.11ax) technology achieves faster speeds, greater capacity and reduced network congestion compared to the previous gen. All WiFi routers require a separate modem. Dual-Band WiFi routers do not support the 6 GHz band.
  • AX1800: Enjoy smoother and more stable streaming, gaming, downloading with 1.8 Gbps total bandwidth (up to 1200 Mbps on 5 GHz and up to 574 Mbps on 2.4 GHz). Performance varies by conditions, distance to devices, and obstacles such as walls.
  • CONNECT MORE DEVICES: Wi-Fi 6 technology communicates more data to more devices simultaneously using revolutionary OFDMA technology
  • EXTENSIVE COVERAGE: Achieve the strong, reliable WiFi coverage with Archer AX1800 as it focuses signal strength to your devices far away using Beamforming technology, 4 high-gain antennas and an advanced front-end module (FEM) chipset
  • OUR CYBERSECURITY COMMITMENT: TP-Link is a signatory of the U.S. Cybersecurity and Infrastructure Security Agency’s (CISA) Secure-by-Design pledge. This device is designed, built, and maintained, with advanced security as a core requirement.

Backend integration timeout

The WebSocket endpoint may accept the connection, but a gateway cannot obtain a timely response from the integration that handles a route or message. This is a backend request problem, not proof that the browser’s opening handshake timed out. Check the gateway and backend logs for the route that was invoked.

Idle connection timeout

The socket opens and carries traffic, then closes after a repeatable period with no traffic. Every intermediary can impose its own idle limit. The shortest limit in the chain—browser-to-server, proxy, load balancer, NAT, firewall, or managed gateway—determines how long an otherwise healthy connection survives.

Unexpected network closure

The connection ends during active use or at a non-repeatable time. A laptop changing networks, a VPN transition, a process restart, a deployment, a browser shutdown, or a transient route failure can all produce this symptom. Capture the close event’s code, reason, and wasClean value before choosing a retry policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Collect evidence before changing timers

Record enough information to reproduce the failure and identify the closing hop.

  1. Write down the endpoint contract. Record the complete ws:// or wss:// URL, hostname, port, path, query parameters, subprotocols, and authentication method. Confirm that the deployed value is not a development URL left in a production build.
  2. Log all four browser events. Log open, message, error, and close. Include a timestamp, close code, reason, and wasClean for every close. The error event often contains little diagnostic detail, so do not discard the later close event.
  3. Inspect the handshake in DevTools. Open the Network panel, filter for WebSocket, select the request, and inspect the handshake headers and Frames or Messages view. A request that never upgrades is a different problem from one that shows frames and then closes.
  4. Measure the idle interval. If closures occur at nearly the same elapsed time after the last frame, compare that interval with the configured idle limits of every intermediary. A repeatable interval is evidence of policy, not random packet loss.
  5. Correlate server-side records. Match the browser timestamp and connection identifier with application logs, reverse-proxy logs, load-balancer logs, and managed-gateway logs. If AWS API Gateway is involved, use CloudWatch logs to identify which component generated the error before changing configuration.
  6. Test the production path. Run the test through the real TLS terminator and proxy. A direct localhost connection bypasses the very intermediary that may be closing the deployed socket.

This small logger gives you a useful baseline:

function watchSocket(ws) {
  const stamp = () => new Date().toISOString();

  ws.addEventListener('open', () => {
    console.log(stamp(), 'open');
  });

  ws.addEventListener('message', event => {
    console.log(stamp(), 'message', event.data);
  });

  ws.addEventListener('error', event => {
    console.error(stamp(), 'error', event);
  });

  ws.addEventListener('close', event => {
    console.warn(stamp(), 'close', {
      code: event.code,
      reason: event.reason,
      wasClean: event.wasClean
    });
  });
}

Fix a handshake that never opens

Verify the URL and transport

Use wss:// when the page is served over HTTPS; browsers generally block an insecure ws:// connection from a secure page. Confirm the host, port, path, and any required query or subprotocol values. A path that is valid for ordinary HTTP may not be the path registered for WebSocket upgrades.

Rank #2
TP-Link AC1200 Gigabit Dual Band WiFi Router (Archer A6) | MU-MIMO Wireless Internet Router, 4 x Antennas, OneMesh and AP Mode, Long Range Coverage
  • Dual band router upgrades to 1200 Mbps high speed internet (300mbps for 2.4GHz plus 900Mbps for 5GHz), reducing buffering and ideal for 4K stream
  • Full Gigabit Ports - Gigabit Router with 4 Gigabit LAN ports, ideal for any internet plan and allow you to directly connect your wired devices
  • Boosted Coverage - Four external antennas equipped with Beamforming technology extend and concentrate the Wi-Fi signals
  • MU-MIMO technology - (5GHz band) allows high speeds for multiple devices simultaneously
  • Access Point Mode - Supports AP Mode to transform your wired connection into wireless network, an ideal wireless router for home

Check authentication at the upgrade boundary

Determine whether the server expects a cookie, an authorization header supplied by your client or library, a query token, or a subprotocol. Cookies are sent according to their domain, path, and SameSite rules. If the server rejects unauthenticated upgrades, the browser may expose only a generic error; the server or gateway log will show the actual status.

Confirm that every proxy forwards the upgrade

The intermediary must pass the WebSocket upgrade request and keep the upgraded connection open. Inspect the handshake in DevTools and the proxy access log together. If the browser receives an ordinary HTTP response, a redirect, or a gateway error instead of an upgrade, fix routing, TLS termination, authentication, or upgrade forwarding before adding a client timeout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an explicit opening timeout

The browser does not provide a built-in connection-timeout option. Wrap the opening event in your own timer so a stalled attempt is closed and reported, then let your reconnect policy decide whether to try again.

function connect(url, timeoutMs = 10000) {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(url);
    let settled = false;

    const timer = setTimeout(() => {
      if (settled) return;
      settled = true;
      ws.close(4000, 'connection timeout');
      reject(new Error('WebSocket connection timeout'));
    }, timeoutMs);

    ws.addEventListener('open', () => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      resolve(ws);
    }, { once: true });

    ws.addEventListener('error', event => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      reject(event);
    }, { once: true });
  });
}

The timer covers only the opening phase. It must not be used as an idle timer after open; idle detection belongs in a heartbeat.

Separate backend integration timeouts from connection timeouts

A managed gateway can accept a WebSocket and still time out while invoking a backend integration. Review the route or message that triggered the failure, then inspect gateway and backend logs for latency, authorization errors, unavailable targets, and responses that never arrived.

Rank #3
Sale
TP-Link AC1200 WiFi Router Dual Band Wireless Internet Router (Archer A54) | 4 x 10/100 Mbps Fast Ethernet Ports, EasyMesh Compatible, Support Guest WiFi, Access Point Mode, IPv6 & Parental Controls
  • Dual-band Wi-Fi with 5 GHz speeds up to 867 Mbps and 2.4 GHz speeds up to 300 Mbps, delivering 1200 Mbps of total bandwidth¹. Dual-band routers do not support 6 GHz. Performance varies by conditions, distance to devices, and obstacles such as walls.
  • Covers up to 1,000 sq. ft. with four external antennas for stable wireless connections and optimal coverage.
  • Supports IGMP Proxy/Snooping, Bridge and Tag VLAN to optimize IPTV streaming
  • Access Point Mode - Supports AP Mode to transform your wired connection into wireless network, an ideal wireless router for home
  • Advanced Security with WPA3 - The latest Wi-Fi security protocol, WPA3, brings new capabilities to improve cybersecurity in personal networks

For AWS API Gateway WebSocket APIs, the current documentation lists an idle connection timeout of 10 minutes, a maximum WebSocket connection duration of 2 hours, and a default integration timeout of 29 seconds. These are different controls:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Limit What it governs Diagnostic implication
10-minute idle connection timeout How long an API Gateway WebSocket can remain without traffic A socket that closes after approximately 10 idle minutes needs traffic or an idle-policy change; inspect all other hops too.
2-hour maximum connection duration The lifetime of one WebSocket connection A long-running client must be prepared to reconnect and restore its subscriptions before or at the end of that lifetime.
29-second default integration timeout The default time allowed for a WebSocket integration to answer A slow route or backend can fail even while the underlying socket remains established.

When AWS is in the path, follow the error source in CloudWatch before changing a client timer. Increasing a browser timeout cannot make a backend respond within the gateway’s integration limit, and sending heartbeats cannot remove a maximum connection duration.

Keep an idle WebSocket alive with an application heartbeat

The browser’s native WebSocket API has no ping() method and does not let browser JavaScript send protocol-level ping frames directly. Send a small application message instead, and require the server to acknowledge it. For example, the client sends {"type":"heartbeat"} and the server replies with {"type":"pong"}. A server library may support protocol ping/pong on the server side, but that capability is separate from the browser API.

Choose interval and response limits from the deployed path

Set the heartbeat interval shorter than the smallest idle limit among the client, proxy, load balancer, NAT, firewall, and gateway. Do not choose values from a direct local test. AWS architecture guidance gives an example of a heartbeat every 30 seconds and declaring failure after 35 seconds without the expected response. That corresponds to a 30-second send interval plus a five-second response window in the client below.

function startHeartbeat(ws, intervalMs = 30000, responseTimeoutMs = 5000) {
  let awaiting = false;
  let responseTimer;
  let stopped = false;

  const onMessage = event => {
    try {
      const message = JSON.parse(event.data);
      if (message.type === 'pong') {
        awaiting = false;
        clearTimeout(responseTimer);
      }
    } catch (_) {
      // Ignore non-JSON application messages.
    }
  };

  const stop = () => {
    if (stopped) return;
    stopped = true;
    clearInterval(interval);
    clearTimeout(responseTimer);
    ws.removeEventListener('message', onMessage);
  };

  const interval = setInterval(() => {
    if (ws.readyState !== WebSocket.OPEN) {
      stop();
      return;
    }

    if (awaiting) {
      ws.close(4000, 'heartbeat timeout');
      stop();
      return;
    }

    awaiting = true;
    ws.send(JSON.stringify({ type: 'heartbeat' }));
    responseTimer = setTimeout(() => {
      if (awaiting && ws.readyState === WebSocket.OPEN) {
        ws.close(4000, 'heartbeat timeout');
      }
    }, responseTimeoutMs);
  }, intervalMs);

  ws.addEventListener('message', onMessage);
  ws.addEventListener('close', stop, { once: true });
  return stop;
}

The server must recognize the heartbeat and send the acknowledgment promptly. Treating any arbitrary incoming message as a pong can hide a broken heartbeat path, so match the message type (and, if needed, a request identifier). Clear the heartbeat when the socket closes, and start a fresh one for each new socket.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
TP-Link Deco X55 AX3000 WiFi 6 Mesh System, Deco X55(3-Pack) | Covers up to 6500 Sq.Ft. , Replaces Wireless Router and Extender, 3 Gigabit ports per unit, supports Ethernet Backhaul
  • Wi-Fi 6 Mesh Wi-Fi - Next-gen Wi-Fi 6 AX3000 whole home mesh system to eliminate weak Wi-Fi for good(2×2/HE160 2402 Mbps plus 2×2 574 Mbps)
  • Whole Home WiFi Coverage - Covers up to 6500 square feet with seamless high-performance Wi-Fi 6 and eliminate dead zones and buffering. Better than traditional WiFi booster and Range Extenders
  • Connect More Devices - Deco X55(3-pack) is strong enough to connect up to 150 devices with strong and reliable Wi-Fi
  • Our Cybersecurity Commitment - TP-Link is a signatory of the U.S. Cybersecurity and Infrastructure Security Agency’s (CISA) Secure-by-Design pledge. This device is designed, built, and maintained, with advanced security as a core requirement
  • More Gigabit Ports - Each Deco X55 has 3 Gigabit Ethernet ports(6 in total for a 2-pack) and supports Wired Ethernet Backhaul for better speeds. Any of them can work as a Wi-Fi Router

Do not confuse heartbeat traffic with application health

A successful pong proves that the path and server process answered that message; it does not prove that a database, subscription, or business operation is healthy. Keep application errors and heartbeat results in separate logs. If the server is overloaded, it may acknowledge a heartbeat while a specific route still exceeds its integration timeout.

Reconnect without creating a retry storm

Reconnect only after a close, not after every error event. The browser can emit both events for one failure. Use bounded exponential backoff with jitter, cap the number of attempts or the total retry time, and reset the delay after a successful open. Do not retry an intentional close or a known authentication failure until credentials or configuration have changed.

function createSocketManager(url, options = {}) {
  const {
    maxAttempts = 8,
    baseDelayMs = 500,
    maxDelayMs = 30000,
    onOpen = () => {},
    onMessage = () => {},
    onGiveUp = () => {}
  } = options;

  let socket = null;
  let heartbeatStop = null;
  let attempt = 0;
  let stopped = false;

  const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

  async function run() {
    while (!stopped && attempt < maxAttempts) {
      try {
        socket = await connect(url);
        attempt = 0;
        heartbeatStop = startHeartbeat(socket);
        socket.addEventListener('message', onMessage);
        onOpen(socket);

        await new Promise(resolve => {
          socket.addEventListener('close', resolve, { once: true });
        });
        heartbeatStop?.();
        heartbeatStop = null;
      } catch (error) {
        // The close path below controls the retry delay.
      }

      if (stopped) break;
      attempt += 1;
      const exponential = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
      const jittered = Math.round(exponential * (0.5 + Math.random()));
      await wait(jittered);
    }

    if (!stopped) onGiveUp();
  }

  return {
    start: run,
    stop() {
      stopped = true;
      heartbeatStop?.();
      socket?.close(1000, 'client shutdown');
    }
  };
}

After reconnecting, re-authenticate if required and re-create subscriptions, room memberships, or server-side filters. A new WebSocket is a new session; assume that state attached to the old connection is gone unless the server explicitly restores it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check every intermediary’s idle policy

List the complete route: browser, local network, corporate proxy or VPN, NAT, firewall, TLS terminator, reverse proxy, load balancer, managed gateway, application server, and any backend integration. Ask where each idle timeout is configured and whether the setting applies to upgraded WebSocket connections as well as ordinary HTTP requests.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Set each intermediary’s idle allowance longer than the heartbeat cycle, or make the heartbeat cycle shorter than the smallest allowance.
  • Ensure the intermediary forwards traffic in both directions; a one-way path can make the client believe a pong never arrived.
  • Check whether a deployment, health check, certificate rotation, or process restart intentionally drains existing connections.
  • Verify that TLS termination forwards the correct host, path, and authentication context to the WebSocket service.
  • Keep server and proxy logs long enough to cover the entire retry sequence, including timestamps and connection identifiers.

If you cannot change a managed gateway’s limit, design around it: send application traffic often enough to avoid the idle limit and reconnect cleanly before the maximum connection duration is reached.

Best Value
TP-Link AXE5400 Tri-Band WiFi 6E Router, 2025 PCMag Editors' Choice | 2.5Gbps WAN Port for Gaming & Streaming, 6GHz Band, 160MHz, OneMesh, Dual-Core CPU, VPN & WPA3 (Archer AXE75)
  • Tri-Band WiFi 6E Router - Up to 5400 Mbps WiFi for faster browsing, streaming, gaming and downloading, all at the same time(6 GHz: 2402 Mbps;5 GHz: 2402 Mbps;2.4 GHz: 574 Mbps)
  • WiFi 6E Unleashed – The 6 GHz band brings more bandwidth, faster speeds, and near-zero latency; Enables more responsive gaming and video chatting
  • Connect More Devices—True Tri-Band and OFDMA technology increase capacity by 4 times to enable simultaneous transmission to more devices
  • Unique Design, More RAM, Better Processing - A unique housing design provides optimal heat dissipation, combined with a 1.0 GHz dual-core CPU and 512 MB High-Speed Memory, the AXE75 is designed for long-term reliability and performance.
  • EasyMesh-compatible - Extend network range even more by adding EasyMesh-compatible routers, extenders, or wireless powerline adapters for a seamless, whole-home connection. Eliminate dead zones, drops, and lag as you move across your home.

Interpret close code 1001 and other closure evidence

Close code 1001 means the peer is going away. It can accompany a deployment, server shutdown, browser navigation, network transition, or intermediary that deliberately ends the connection. It is not, by itself, proof of a JavaScript timeout. Read the close reason when present, compare the timestamp with server and gateway logs, and check whether the closure is clean.

A clean close with a meaningful reason usually indicates an intentional decision by the application or intermediary. An unclean close, an empty reason, or a missing server log points toward an abrupt network or process failure. Your recovery code should treat unexpected closures as reconnect candidates, while respecting intentional shutdowns and authentication errors.

Use a test matrix that matches production

Run the same client build through each relevant route and record the last frame, elapsed idle time, close event, and server-side observation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Test What it isolates What to record
Direct local server Client and application behavior without deployed intermediaries Opening time, heartbeat acknowledgment, and close handling
Production hostname over TLS Certificate, DNS, TLS termination, routing, and authentication Handshake result and proxy or gateway log entry
Production path while idle Shortest intermediary idle timeout Exact time since the last application frame and close code
Slow backend route Integration timeout rather than socket establishment Gateway route, backend latency, and integration error
Network change or process restart Unexpected closure and reconnect behavior Backoff sequence, duplicate sockets, and subscription restoration

Leave the browser’s Frames view open during the idle test. If heartbeat frames stop appearing, debug the client timer or page lifecycle. If frames continue but acknowledgments stop, debug the server or path. If both sides log healthy traffic but the browser closes, inspect the intermediary that sits between them.

Common fixes that do not solve the real problem

  • Calling ws.ping() in browser code: there is no native method. Send an application heartbeat and require an acknowledgment.
  • Increasing the opening timeout: this only makes a stalled handshake take longer to fail; it does not alter a proxy idle policy or a backend integration limit.
  • Using a heartbeat longer than the shortest idle limit: the intermediary can close the socket before the next heartbeat arrives.
  • Testing only on localhost: the local route bypasses the TLS terminator, proxy, load balancer, and gateway that operate in production.
  • Reconnecting on every error event: one failure can produce both error and close events, creating duplicate sockets and a retry storm.
  • Keeping the old subscription state: after reconnect, explicitly re-authenticate and rehydrate subscriptions instead of assuming the server retained them.
  • Changing AWS settings without checking CloudWatch: first identify whether the observed failure is the 10-minute idle limit, the 29-second integration timeout, or another component.

A practical decision guide

Observed symptom First control point Best next action Recovery approach
No open event or failed upgrade Browser URL, authentication, TLS, proxy, or gateway handshake Inspect the handshake request and server access logs Fix configuration; retry only after the cause is corrected
Socket opens but a route exceeds its limit Backend integration and managed gateway Trace the route in gateway and backend logs Optimize or split the operation; do not hide it with a client timer
Closure after repeatable idle period Shortest intermediary idle timeout Measure last-frame-to-close time and add a shorter heartbeat Reconnect after a missed acknowledgment
Close code 1001 during deploy or network change Server lifecycle or network path Correlate close time with deployment and infrastructure logs Use bounded backoff and restore session state
Repeated failures with no stable open Authentication, endpoint, or unavailable service Stop rapid retries and surface the original error Cap attempts and require a configuration or credential change

If WebSocket failures occur alongside broader Windows crashes or system connectivity problems, Outbyte PC Repair is an optional shortcut for checking more than 100 common Windows issues, reducing selected CPU, RAM, and disk load, cleaning temporary and cache files, and reviewing vulnerability-related settings. It runs on Windows 11, 10, 8, and 7; its free trial is offered by category for at least two days before a paid subscription. It complements antivirus software rather than replacing it, and results vary—no tool repairs every WebSocket failure.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

AWS API GatewayJavaScriptTroubleshootingWeb developmentWebSocket

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.