Node.js HTTP API for Browsers

3.2.0 · active · verified Wed Apr 22

stream-http is a JavaScript library designed to provide a browser-compatible implementation of Node.js's native `http` module. Its primary goal is to replicate the Node.js HTTP client API and behavior as closely as possible within the constraints of web browsers, making it suitable for projects that need consistent HTTP request handling across Node.js and browser environments. The package is currently at version 3.2.0 and appears to be actively maintained, indicated by recent feature additions and ongoing support for modern browser capabilities. A key differentiator is its emphasis on streaming, delivering data to the caller before the request fully completes. It supports true streaming with backpressure in Chrome >= 58 via `fetch` and `WritableStream`, true streaming in Chrome >= 43 (via `fetch`) and Firefox >= 9 (via `moz-chunked-arraybuffer`), and pseudo-streaming in other supported browsers where the full response is held in memory but available early. It aims to replace `http-browserify`. It also provides additional browser-specific features like `message.url` for redirects and `options.withCredentials` for CORS requests.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to make a GET request using the `http.request` method, similar to Node.js. It shows how to set request options, handle the response stream, and process incoming data chunks until the request ends, including error handling.

import http from 'stream-http';

// Example: Fetch data from a public API
const options = {
  host: 'jsonplaceholder.typicode.com',
  path: '/posts/1',
  method: 'GET'
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log('No more data in response.');
    try {
      const parsedData = JSON.parse(data);
      console.log('Response body:', parsedData);
    } catch (e) {
      console.error('Failed to parse JSON:', e);
      console.log('Raw response body:', data);
    }
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

req.end();

view raw JSON →