{"id":12872,"library":"bare-http-parser","title":"Bare HTTP Parser","description":"bare-http-parser is a streaming HTTP request and response parser specifically designed for the Bare JavaScript runtime. Bare is a lightweight, modular runtime optimized for desktop and mobile environments, emphasizing embedded and cross-device support, particularly for peer-to-peer applications. This library, currently at version 1.1.3, provides the foundational capability to interpret raw HTTP stream data efficiently within the Bare ecosystem. Unlike traditional HTTP parsers that might operate on complete buffered messages, bare-http-parser processes data as it arrives, making it suitable for low-latency network operations characteristic of peer-to-peer systems. Its release cadence aligns with the development of the broader Holepunch/Bare project, with updates typically coinciding with advancements in the runtime itself. This parser is a critical component for building HTTP-based networking features directly within Bare applications, leveraging its stream-first architecture.","status":"active","version":"1.1.3","language":"javascript","source_language":"en","source_url":"https://github.com/holepunchto/bare-http-parser","tags":["javascript"],"install":[{"cmd":"npm install bare-http-parser","lang":"bash","label":"npm"},{"cmd":"yarn add bare-http-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add bare-http-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While Bare supports both ESM and CJS, ESM import syntax is preferred. CommonJS require() will work but is considered legacy for new development.","wrong":"const { HTTPRequestParser } = require('bare-http-parser')","symbol":"HTTPRequestParser","correct":"import { HTTPRequestParser } from 'bare-http-parser'"},{"note":"Used for parsing incoming HTTP response streams. Ensure proper stream handling to avoid data loss or parsing errors.","wrong":"const { HTTPResponseParser } = require('bare-http-parser')","symbol":"HTTPResponseParser","correct":"import { HTTPResponseParser } from 'bare-http-parser'"},{"note":"Error classes are exported from a dedicated subpath for better modularity and tree-shaking.","wrong":"import { HTTPParserError } from 'bare-http-parser'","symbol":"HTTPParserError","correct":"import { HTTPParserError } from 'bare-http-parser/errors'"}],"quickstart":{"code":"import { HTTPRequestParser, HTTPResponseParser } from 'bare-http-parser';\nimport { Buffer } from 'buffer'; // Bare provides a Buffer implementation\n\nconst rawRequest = Buffer.from(\n  'GET /hello HTTP/1.1\\r\\n'\n  + 'Host: example.com\\r\\n'\n  + 'User-Agent: bare-client/1.0\\r\\n'\n  + 'Content-Length: 13\\r\\n'\n  + '\\r\\n'\n  + 'Hello, World!'\n);\n\nconst requestParser = new HTTPRequestParser();\nlet parsedRequest = { headers: {}, method: '', url: '', body: '' };\n\nrequestParser.on('headers', (headers) => {\n  parsedRequest.headers = Object.fromEntries(headers);\n});\nrequestParser.on('request', (requestLine) => {\n  parsedRequest.method = requestLine.method;\n  parsedRequest.url = requestLine.url;\n});\nrequestParser.on('data', (chunk) => {\n  parsedRequest.body += chunk.toString();\n});\nrequestParser.on('end', () => {\n  console.log('Parsed Request:', parsedRequest);\n  if (parsedRequest.body !== 'Hello, World!') {\n    console.error('Request body mismatch!');\n  }\n});\nrequestParser.on('error', (err) => {\n  console.error('Request parsing error:', err.message);\n});\n\nrequestParser.write(rawRequest);\nrequestParser.end();\n\nconst rawResponse = Buffer.from(\n  'HTTP/1.1 200 OK\\r\\n'\n  + 'Content-Type: text/plain\\r\\n'\n  + 'Content-Length: 12\\r\\n'\n  + '\\r\\n'\n  + 'Hello client'\n);\n\nconst responseParser = new HTTPResponseParser();\nlet parsedResponse = { headers: {}, statusCode: 0, statusMessage: '', body: '' };\n\nresponseParser.on('headers', (headers) => {\n  parsedResponse.headers = Object.fromEntries(headers);\n});\nresponseParser.on('response', (statusLine) => {\n  parsedResponse.statusCode = statusLine.statusCode;\n  parsedResponse.statusMessage = statusLine.statusMessage;\n});\nresponseParser.on('data', (chunk) => {\n  parsedResponse.body += chunk.toString();\n});\nresponseParser.on('end', () => {\n  console.log('Parsed Response:', parsedResponse);\n  if (parsedResponse.body !== 'Hello client') {\n    console.error('Response body mismatch!');\n  }\n});\nresponseParser.on('error', (err) => {\n  console.error('Response parsing error:', err.message);\n});\n\nresponseParser.write(rawResponse);\nresponseParser.end();","lang":"javascript","description":"This example demonstrates parsing a raw HTTP request and response using `HTTPRequestParser` and `HTTPResponseParser` classes, handling streaming data and event emission for headers, request/response lines, and body data."},"warnings":[{"fix":"Implement explicit timeout mechanisms and 'error' event listeners. Validate parsed content lengths against actual received body data. For `Content-Length` mismatches, consider the stream closed prematurely.","message":"As a streaming parser, `bare-http-parser` requires careful handling of incomplete or malformed HTTP streams. If a stream ends prematurely (e.g., connection closes before Content-Length bytes are received), the parser may not emit an 'end' event for the body, potentially leading to incomplete data. Ensure stream integrity or implement robust error recovery for network failures.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Prefer ESM `import` syntax. If encountering issues with `require()`, explicitly check the package's `exports` map in its `package.json` for correct paths and module types. Ensure your project's `tsconfig.json` (if using TypeScript) or build configuration is aligned with the target module system.","message":"Interoperability between CommonJS (CJS) and ES Modules (ESM) in JavaScript runtimes, including Bare, can be complex, especially with default vs. named imports. While Bare aims for bidirectional interoperability, unexpected behavior can arise when mixing module types or consuming packages compiled with different transpiler assumptions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When processing headers, iterate over the raw headers array (e.g., `[['Header-Name', 'value1'], ['Header-Name', 'value2']]`) and store values in an array for multi-value headers, rather than overwriting them in a simple object. For example, `headers[name].push(value)`.","message":"HTTP headers can occasionally contain duplicate keys (e.g., 'Set-Cookie'). The parser provides raw header arrays where duplicates may exist. Directly converting these to a simple object (`Object.fromEntries`) will only retain the last value for a given header name, potentially losing information.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you are using named imports: `import { HTTPRequestParser } from 'bare-http-parser';` for ESM, or `const { HTTPRequestParser } = require('bare-http-parser');` for CommonJS.","cause":"Attempting to use `HTTPRequestParser` (or `HTTPResponseParser`) without correctly importing it from the module. This often happens with incorrect CommonJS `require()` syntax or trying to use a non-existent default export.","error":"TypeError: HTTPRequestParser is not a constructor"},{"fix":"Implement comprehensive error handling on the parser's 'error' event and the underlying stream's 'close' or 'end' events. Consider adding timeouts to detect stalled connections. For client applications, retry logic might be necessary. For servers, send an appropriate HTTP error response.","cause":"The underlying stream or connection was closed before the HTTP message parsing was complete, typically indicating truncated data or a network issue.","error":"Error: premature close"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":null}