Socket Hang Up Error
Fix 'socket hang up' errors in Node.js HTTP clients. Learn why connections are terminated prematurely and how to handle them.
What Does This Error Mean?
The 'socket hang up' error means an HTTP connection was terminated by the server before the request completed. This usually happens when the server closes the connection or the underlying TCP connection is reset (ECONNRESET).
Common Causes
Server crashed or was killed while processing the request
Server-side timeout closing idle connections
Nginx or load balancer timeout configured too low
Client request body is too large for the server
HTTP/2 or keep-alive connection was forcefully closed
Network proxy or firewall resetting the connection
How to Fix It
Add retry logic with exponential backoff
Retry failed requests with increasing delays between attempts.
async function fetchWithRetry(url, options, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const res = await fetch(url, options)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res
} catch (err) {
if (i === retries - 1) throw err
const delay = Math.pow(2, i) * 1000
console.log(`Retry ${i + 1}/${retries} after ${delay}ms`)
await new Promise(r => setTimeout(r, delay))
}
}
}Increase timeout settings
Ensure timeout values are appropriate for the server's expected response time.
// Node.js HTTP agent keep-alive
const http = require("http")
const agent = new http.Agent({ keepAlive: true })
// Fetch with timeout
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30000)
fetch(url, { signal: controller.signal, agent })Check server logs for crashes
A socket hang up during request processing often means the server crashed.
# Check Node.js error logs pm2 logs journalctl -u myapp # Check for out-of-memory errors dmesg | grep -i "killed process"
Use connection pooling
Reuse connections with keep-alive to avoid establishing new connections for each request.
const keepAliveAgent = new https.Agent({ keepAlive: true })
// Reuse the same agent across requests
fetch(url1, { agent: keepAliveAgent })
fetch(url2, { agent: keepAliveAgent })Related Tools
Use these tools to debug and fix this error:
Related Errors
Other common errors in this category:
401 Unauthorized Error
Learn what a 401 Unauthorized error means, common causes, and how to fix authentication failures in your web applications.
403 Forbidden Error
Learn what 403 Forbidden means, how it differs from 401, and how to fix access denied errors in your applications.
404 Not Found Error
Learn what 404 Not Found means, common causes, and how to fix broken links and missing resources on your website or API.
429 Too Many Requests Error
Learn what 429 Too Many Requests means, how rate limiting works, and how to handle or avoid hitting API rate limits.