Error: socket hang up in Node.js [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
7 min

banner

# Error: socket hang up in Node.js [Solved]

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.

index.js
// 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.

shell
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

error socket hang up

The error is thrown when the server never sends a response.

The error most commonly occurs for 2 reasons:

  • If you are the client (browser) and send a request to a server and the request times out. In this case, the "socket hang up" error is raised and you have to handle it using a 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.

  • If you are the server (or a proxy server) and have received a request from a client (browser) and started processing the request, the client could cancel the request before you've responded.

This also causes the socket hang-up error.

This might happen if the client (browser) initiates a request, perhaps the request takes too long and the user then refreshes the page and cancels the request.

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.

index.js
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.

shell
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.

index.js
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().

index.js
req.end();

Here is an example that wraps the request in a try/catch block to handle the error.

index.js
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.

# Make sure the specified protocol is correct (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.

index.js
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.

shell
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.

Make sure you are importing the 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.

index.js
// โœ… 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://.

# Make sure the path is prefixed with / if you use Node.js with Express.js

The 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.

shell
# โ›”๏ธ Incorrect (causes the error) api/users

Whereas the following path is correct and doesn't cause the error.

shell
# โœ… Correct (has the / prefix) /api/users

Notice that we prefixed the path with a forward slash /.

# The request payload you're sending might be too large

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.

# Set the request timeout

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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().

index.js
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:

  1. Set the axios timeout property in the request config object.
  2. Make sure to handle the error in your catch() method or .catch() (if using .then()).
index.js
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).

index.js
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.

index.js
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.

index.js
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev