Bare HTTP/1 Library

4.5.6 · active · verified Wed Apr 22

bare-http1 is a low-level, native HTTP/1 library for JavaScript, designed for efficient and direct interaction with the HTTP/1 protocol without higher-level abstractions. It provides fundamental primitives for creating HTTP/1 servers and clients, making it suitable for environments where fine-grained control or minimal overhead is paramount. The current stable version is 4.5.6, indicating ongoing maintenance and incremental improvements, as shown by recent patch releases addressing stability. Key differentiators include its 'bare' philosophy, focusing solely on HTTP/1, and its light footprint, often used in conjunction with other 'bare-' ecosystem modules like bare-buffer and bare-url for buffer and URL handling. It ships with TypeScript types, facilitating robust development in TypeScript projects and ensuring type safety.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a basic HTTP/1 server that listens on a random port, then makes a client request to that server, logging the response body. It showcases the core `createServer` and `request` functions for fundamental HTTP/1 communication and includes basic error handling.

import { createServer, request } from 'bare-http1';
import { Buffer } from 'bare-buffer';

const server = createServer((req, res) => {
  console.log(`Server received request: ${req.method} ${req.url}`);
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Content-Length', 12);
  res.write('hello world!');
  res.end();
});

server.listen(0, () => {
  const { port } = server.address() as { port: number };
  console.log('Server is bound on port', port);

  const client = request({ port, method: 'GET', path: '/' }, (res) => {
    console.log(`Client received response: ${res.statusCode}`);
    const chunks: Buffer[] = [];
    res.on('data', (data) => chunks.push(Buffer.from(data)));
    res.on('end', () => {
      console.log('Client received data:', Buffer.concat(chunks).toString());
      server.close(() => console.log('Server closed.'));
    });
  });
  client.end();
});

server.on('error', (err) => {
  console.error('Server error:', err);
});

view raw JSON →