Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to set a timeout on a http.request() in Node?

Timeout on HTTP request in Node.js using http.request(), req.socket.setTimeout() and req.socket.on('timeout')

Quick Answer: Use the timeout option when creating the request options object, e.g. var options = { ... headers: ..., socketTimeout: myTimeout }

To set a timeout on an HTTP client that uses http.request, you need to pass the timeout option when creating the request options. This is because setting the socket timeout after creating the request object does not work.

💡 Why You Are Getting This Error

  • [Cause]

🔧 Proven Troubleshooting Steps

Method 1: Setting Timeout in Request Options

  1. Step 1: Create the request options with the timeout option.

Example:

var options = { hostname: 'example.com', port: 80, path: '/', method: 'GET', timeout: 5000 };
  • Step 2: Create the request object and set up the callback function.
  • 🎯 Final Words

    By setting the timeout option when creating the request options, you can ensure that your HTTP client times out after a specified amount of time if no data is received. This helps prevent resource starvation and ensures that your application remains responsive.

    Did this fix your problem?

    If not, try searching for specific error codes.

    🔍 Search Error Database

    ❓ Frequently Asked Questions