Skip to content

ublitzjs/headers

Repository files navigation

@ublitzjs/headers module with parser of "Range" HTTP header and TypeScript docs for HTTP headers

μBlitz.js

A blazing-fast, ultra-optimized utility package for managing, serializing, and parsing HTTP headers. Built specifically for high-performance Node.js environments (like uWebSockets.js), this package streamlines common header operations, enforces strict security defaults, and maximizes throughput by eliminating redundant runtime operations.

Features

  • ⚡ Performance Optimized: Functions like staticHeaders allow raw serialization to bypass expensive multiple native framework calls (e.g., res.writeHeader in uWebSockets.js).
  • 🛡️ Secure Defaults Built-in: Full, zero-overhead production defaults cloned from the trusted helmet security package.
  • 🎯 Strict Range Parser: A parseSingleBytesRange implementation that is 2x to 4x faster than range-parser, safely dropping rarely-used multi-range complexities in compliance with RFC 9110.
  • 📦 Strongly Typed: Full TypeScript support with comprehensive autocompletion for standard, experimental, and custom headers.
  • Distributed as ESM and CJS
  • Tested: All utilities are stable and parseSingleBytesRange passes same tests as "range-parser" with several custom ones
  • No runtime dependencies

Installation

bun add @ublitzjs/headers

API & Functionality Overview

  1. High-Performance Headers Serialization

staticHeaders(headers)

Concatenates an object of HTTP headers into a single flattened string, intentionally omitting the final trailing \r\n (CRLF).

Purpose: Designed as a compile-time or setup-phase optimization step. By creating a pre-serialized block of headers, you can feed them directly into high-speed servers like uWebSockets.js in a single pass instead of making multiple overhead-heavy native calls.

import { staticHeaders } from '@ublitzjs/headers';
import uWS from 'uWebSockets.js';
// or import uWS from "uwsjs-fork"

// Pre-serialize standard static headers
const fastHeaders = staticHeaders({
  "Content-Type": "text/plain",
  "Cache-Control": "public, max-age=3600"
});

uWS.App().get("/", (res) => {
  // Drastic speedup by passing your pre-joined block into one writeHeader execution
  res.writeHeader(fastHeaders, "");
  res.end("Hello World");
});
  1. Header Parsing & Protocol Utilities

parseSingleBytesRange(range, resourceSize, maxChunk?)

An ultra-optimized variant of range-parser (2x-4x) designed explicitly for a single byte-range sequence starting with bytes=. According to RFC 9110, servers are fully permitted to reject complex multi-range requests, which this utility does to guarantee maximum processing speed. Benchmarks: NodeJS Bun

  • Strictness: More strict than traditional parsers; it directly rejects non-integer limits based on RFC criteria.

  • Parameters:

      range (string): The raw header string (e.g., "bytes=0-999", "bytes=-500", "bytes=300-").
    
      resourceSize (number): The true boundary size of your file/buffer.
    
      maxChunk (number, optional): Forces a cap on the slice sizes returned (ideal for stream-chunk throttling).
    

Returns:

// On Failure
{ err: -1 | -2 } // -1 = Unsatisfiable Range, -2 = Malformed / Multi-range

// On Success
{ err: 0, start: number, end: number }

Example:

import { parseSingleBytesRange } from '@ublitzjs/headers';

const result = parseSingleBytesRange("bytes=0-999", 500, 200);
// Returns: { err: 0, start: 0, end: 199 } (Capped implicitly by maxChunk)

typedAllowHeader(methodsArr)

Accepts an array of lowercase, non-repeating HTTP methods and converts them cleanly into a valid, standard-compliant Allow header text block.

Key Behaviors:

  • Automatically maps shorthands like "del" to full standard format ("DELETE").

  • Safely ignores non-REST network structures like "ws" (WebSockets).

Example:

import { typedAllowHeader } from '@ublitzjs/headers';

const allowStr = typedAllowHeader(['get', 'post', 'del', 'ws']);
// Returns: "GET, POST, DELETE"
  1. Security Headers Management (Helmet-inspired)

helmentHeaders

An exported object configuration containing default security-hardened headers identical to the helmet configuration.

// Defaults exported automatically:
{
  "X-Content-Type-Options": "nosniff",
  "X-DNS-Prefetch-Control": "off",
  "X-Frame-Options": "DENY",
  "Referrer-Policy": "same-origin",
  "X-Permitted-Cross-Domain-Policies": "none",
  "X-Download-Options": "noopen",
  "Cross-Origin-Resource-Policy": "same-origin",
  "Cross-Origin-Opener-Policy": "same-origin",
  "Cross-Origin-Embedder-Policy": "require-corp", // Enables SharedArrayBuffer usage
  "Origin-Agent-Cluster": "?1"
}

setCSP(mainCSP, ...remove)

Generates an explicit Content-Security-Policy (CSP) string directly based on defined directories, with an integrated mechanism to safely filter out parameters dynamically.

Example:

import { setCSP, CSPDirs } from '@ublitzjs/headers';

const cspHeader: string = setCSP({
  ...CSPDirs,
  "upgrade-insecure-requests": []
});

Type Interfaces

The package exposes robust type constraints guaranteeing you do not introduce typo bugs or invalid configurations:

// Complete base types combining basic, helmet, experimental, and CORS headers
type RequiredBaseHeadersT = (simpleHeadersT & helmetHeadersT & experimentalHeadersT & CORSHeadersT);

// Fallback catch type allowing arbitrary custom headers alongside standard types
type BaseHeadersT = Partial<RequiredBaseHeadersT & { [key: string]: string; }>;

// Lowercase type map utilities
type lowHeadersT = Lowercase<keyof RequiredBaseHeadersT>;

About

TypeScript collection of HTTP headers + some helpers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Generated from Guthib-of-Dan/lib_arch