Extract URL from Node.js HTTP ClientRequest

1.1.0 · maintenance · verified Wed Apr 22

The `http-request-to-url` package provides a focused utility function designed to extract the complete URL (including protocol, host, port, path, and query string) from a Node.js `http.ClientRequest` object. This is particularly useful in scenarios where an outgoing HTTP request has been initiated, and its full destination URL needs to be programmatically determined for purposes such as logging, proxying, or debugging. The package currently resides at version 1.1.0. Given its last commit date in 2019, it appears to be in a maintenance state, offering stable functionality primarily for CommonJS environments and leveraging standard Node.js `http` module properties without frequent updates or new feature development. Its differentiator is its singular purpose, directly addressing the extraction of a URL from a low-level Node.js request object.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create an `http.ClientRequest` and use `httpRequestToUrl` to extract its full target URL.

const httpRequestToUrl = require('http-request-to-url');
const http = require('http');

async function getRequestUrl() {
  const targetUrl = 'http://jsonplaceholder.typicode.com/posts/1?userId=1';
  // Create a client request without sending it immediately
  const clientRequest = http.request(targetUrl, {
    method: 'GET',
    headers: {
      'Accept': 'application/json'
    }
  }, (res) => {
    // Consume response data to prevent memory leaks
    res.resume(); 
  });

  clientRequest.end(); // Send the request

  try {
    const resolvedUrl = await httpRequestToUrl(clientRequest);
    console.log(`Resolved URL: ${resolvedUrl}`);
  } catch (error) {
    console.error(`Error resolving URL: ${error.message}`);
  }
}

getRequestUrl();

view raw JSON →