Last updated: Apr 5, 2024
Reading timeยท7 min
The Node.js error "socket hang up" occurs when the socket doesn't send the
connection end
event within the timeout period.
In most cases, you can solve the error by calling req.end()
or res.end()
on the server to finish sending the request.
// Add this after your request // to finish sending the request // ๐๏ธ without a message res.end() res.end('Response sent message')
Here is the complete stack trace.
Trace: { [Error: socket hang up] code: 'ECONNRESET' } Error!: Error: socket hang up using https://example.com Error: socket hang up at createHangUpError at Socket.socketOnEnd [as onend] at Socket.g at Socket.EventEmitter.emit at _stream_readable.js:910:16 at process._tickCallback
The error is thrown when the server never sends a response.
The error most commonly occurs for 2 reasons:
try/catch
block.You can then retry the request or queue it for it to be retried at a later point in time.
The server might've also crashed while processing the request or the server might've simply refused the connection.
This also causes the socket hang-up error.
The previous request is canceled (which causes the error on the server- side).
In these cases, you can handle the error in a try/catch block.
Here is an example code sample that causes the error.
import https from 'https'; // ๐๏ธ If you use CommonJS require() // const https = require('https') const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', }; const req = https.request(options, function (res) { console.log(res.statusCode); }); console.log(req);
Running the code sample above produces the following error message.
node:events:489 throw er; // Unhandled 'error' event ^ Error: socket hang up at connResetException (node:internal/errors:714:14) at TLSSocket.socketOnEnd (node:_http_client:519:23) at TLSSocket.emit (node:events:523:35) at endReadableNT (node:internal/streams/readable:1367:12) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) Emitted 'error' event on ClientRequest instance at:
We started an HTTPS request but we never ended it so it timed out without a response.
To solve the error, call the req.end()
method at the end of the request.
import https from 'https'; // ๐๏ธ If you use CommonJS require() // const https = require('https') const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', }; const req = https.request(options, function (res) { console.log(res.statusCode); }); console.log(req); // โ Call req.end here to solve the error req.end();
The only line that was needed was calling req.end()
.
req.end();
Here is an example that wraps the request in a try/catch
block to handle the
error.
import https from 'https'; // ๐๏ธ If you use CommonJS require() // const https = require('https') try { const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', }; const req = https.request(options, function (res) { console.log(res.statusCode); }); console.log(req); req.end(); } catch (err) { console.log(err.message); // Handle the request here // e.g. by re-initiating the request // or queuing the request for later }
If an error occurs in the try
block, it gets passed to the catch()
method
where you can handle it.
You could re-initiate the request or queue it for later.
http://
vs https://
)Make sure the specified protocol is correct when issuing requests.
For example, the following code sample causes the "socket hang up" error.
import http from 'http'; // ๐๏ธ If you use CommonJS require() // const http = require('http') const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', }; const req = http.request(options, function (res) { console.log(res.statusCode); }); console.log(req); req.end();
Running the code sample produces the following error.
node:events:489 throw er; // Unhandled 'error' event ^ Error: socket hang up
Notice that we imported the http
module from http
and tried to issue an
HTTPS request.
Port 443 is for HTTPS connections and port 80 is for HTTP connections.
https
module if you need to issue an HTTPS request and the http
module if you need to issue an HTTP request.We have to issue an HTTPS request in the example (port 443), so we can solve the
error by importing the https
module instead.
// โ Works as expected import https from 'https'; // ๐๏ธ if you use CommonJS require() // const https = require('https') const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', }; const req = https.request(options, function (res) { console.log(res.statusCode); }); console.log(req); req.end();
Another common cause of the error is trying to connect to a web sockets server
using the ws://
protocol instead of wss://
.
If the server is secure, use wss://
and if the server is NOT secure, use
ws://
.
/
if you use Node.js with Express.jsThe error is also caused if you forget to prefix the path to which you're making a request with a forward slash.
For example, the following path is incorrect and causes the error.
# โ๏ธ Incorrect (causes the error) api/users
Whereas the following path is correct and doesn't cause the error.
# โ Correct (has the / prefix) /api/users
Notice that we prefixed the path with a forward slash /
.
Another common cause of the "socket hang up" error is that the request payload (data) that is sent to the server is too large.
In this case, you have to reduce the amount of data you're sending to the server (e.g. by sending it in multiple requests).
You can try to send the same request using Postman or any other HTTP client to verify that the issue isn't in the browser that initiates the request.
If the error persists, try to set the request timeout.
For example, if you get the error when creating a server in Node.js, set the keep-alive header.
import http from 'http'; const server = http.createServer( {keepAlive: true}, (req, res) => { // your code // If you need to send back a response res.end('Example response sent message'); }, ); // Set the timeout to 4000 milliseconds (4 seconds) server.keepAliveTimeout = 4000;
The Keep-Alive
header manages the sockets for client-side HTTP connections.
The server.keepAliveTimeout property is the number of milliseconds of inactivity a server needs to wait for additional incoming data after it has finished writing the last response before a socket is destroyed.
If you get the error when issuing an HTTPS or an HTTP request, try to set the
agent
property in the options
object.
import https from 'https'; // ๐๏ธ If you use CommonJS require() // const https = require('https') const options = { host: 'en.wikipedia.org', path: '/wiki/Albert_Einstein', port: 443, method: 'GET', agent: https.Agent({keepAlive: true}), }; const req = https.request(options, function (res) { console.log(res.statusCode); }); req.end();
The example above issues an HTTPS request.
If you use the http
module, make sure to use the http.Agent
property
instead.
import http from 'http'; // ๐๏ธ If you use CommonJS require() // const http = require('http') const options = { host: 'example.com', path: '/your/path', port: 443, method: 'GET', // ๐๏ธ Using http.Agent instead agent: http.Agent({keepAlive: true}), }; const req = https.request(options, function (res) { console.log(res.statusCode); }); req.end();
You can also do this when issuing HTTP requests or in an Express.js application.
req.setTimeout(5000);
The only parameter we passed to req.setTimeout
is the number of milliseconds
before the request times out.
5000 milliseconds are equal to 5 seconds.
You could optionally pass a callback function as the second parameter to
req.setTimeout()
.
req.setTimeout(5000, () => { console.log('This function is called when a timeout occurs'); });
The callback function gets invoked when a timeout occurs.
If you got the error when issuing an axios
request:
timeout
property in the
request config object.catch()
method or .catch()
(if
using .then()).import axios from 'axios'; // ๐๏ธ If you use CommonJS require() // const axios = require('axios'); async function getPosts() { try { const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { timeout: 5000, headers: { Accept: 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } getPosts().then(result => { console.log(result); });
Notice that we set the timeout
property to 5000
milliseconds (5 seconds).
const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { timeout: 3000, }, );
Make sure to handle the error in the catch()
method as shown in the code
sample.
If you need to define a custom agent to be used when performing HTTP and HTTPS
requests in Node.js, set the httpAgent
or httpsAgent
properties.
import https from 'https'; // ๐๏ธ For CommonJS require() // const https = require('https'); const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { timeout: 3000, // ๐๏ธ httpsAgent: new https.Agent({ keepAlive: true }), }, );
When issuing HTTP requests, set the httpAgent
property instead.
import http from 'http'; // ๐๏ธ For CommonJS require() // const https = require('https'); const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { timeout: 3000, // ๐๏ธ httpAgent: new https.Agent({ keepAlive: true }), }, );
I've also written a detailed guide on how to handle timeouts in axios.
You can learn more about the related topics by checking out the following tutorials: