or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-on-headers

Execute a listener when a response is about to write headers

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/on-headers@1.1.x

To install, run

npx @tessl/cli install tessl/npm-on-headers@1.1.0

index.mddocs/

on-headers

Overview

A lightweight Node.js utility that executes listeners when HTTP response headers are about to be written. This package provides a simple hook mechanism for the HTTP response lifecycle, allowing developers to modify headers, add security measures, or perform logging right before headers are sent to the client.

Key Features:

  • Hook into the HTTP response lifecycle before headers are sent
  • Support for multiple listeners with reverse-order execution
  • Compatible with native Node.js HTTP module and frameworks like Express
  • Minimal overhead with single-execution guarantee
  • Built-in error handling for invalid arguments

Package Information

  • Package Name: on-headers
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install on-headers

Core Imports

var onHeaders = require('on-headers');

Note: This package uses CommonJS and does not provide native ES module exports. For ES module environments, use dynamic imports:

const { default: onHeaders } = await import('on-headers');

Architecture

The on-headers package works by intercepting the Node.js HTTP response lifecycle. It hooks into the writeHead method of the ServerResponse object, allowing listeners to execute right before headers are sent to the client.

Key Components:

  • Hook Mechanism: Replaces the original writeHead method with a wrapper function
  • Listener Queue: Maintains listeners in registration order, executes in reverse order
  • Single Execution: Ensures listeners fire only once per response, even with multiple writeHead calls
  • Context Binding: Binds the response object as this context to listener functions

Basic Usage

var http = require('http');
var onHeaders = require('on-headers');

http
  .createServer(onRequest)
  .listen(3000);

function addPoweredBy() {
  // set if not set by end of request
  if (!this.getHeader('X-Powered-By')) {
    this.setHeader('X-Powered-By', 'Node.js');
  }
}

function onRequest(req, res) {
  onHeaders(res, addPoweredBy);

  res.setHeader('Content-Type', 'text/plain');
  res.end('hello!');
}

Capabilities

Header Listener Registration

Registers a listener function to execute when HTTP response headers are about to be written. The listener receives the response object as its context and can modify headers before they are sent to the client.

/**
 * Execute a listener when a response is about to write headers
 * @param {ServerResponse} res - HTTP response object (ServerResponse instance)
 * @param {HeaderListener} listener - Callback function to execute when headers are about to be written
 * @throws {TypeError} When res argument is missing
 * @throws {TypeError} When listener is not a function
 */
function onHeaders(res, listener);

/**
 * Header listener function that executes before headers are written
 * @callback HeaderListener
 * @this {ServerResponse} The HTTP response object
 */
typedef HeaderListener = () => void;

Key behaviors:

  • Context Binding: The listener function is called with the response object as its context (this), providing direct access to this.setHeader(), this.getHeader(), this.statusCode, etc.
  • Single Emission: Headers are considered emitted only once, right before being sent to the client
  • Reverse Order Execution: Multiple listeners on the same response fire in reverse order of registration (last registered fires first)
  • Single Execution Guarantee: The listener will only fire once per response, even if writeHead is called multiple times
  • Mutable Response: The response object can be modified within the listener (headers, status code, etc.) before being sent to the client
  • Timing: Listeners execute after all application code but before headers reach the client

Multiple Listeners Example:

var http = require('http');
var onHeaders = require('on-headers');

function onRequest(req, res) {
  // These will fire in reverse order: listener3, listener2, listener1
  onHeaders(res, function listener1() {
    console.log('First registered, fires last');
  });
  
  onHeaders(res, function listener2() {
    console.log('Second registered, fires second');
  });
  
  onHeaders(res, function listener3() {
    console.log('Third registered, fires first');
  });

  res.end('done');
}

Header Modification Example:

var onHeaders = require('on-headers');

function setDefaultHeaders() {
  // Add security headers if not already set
  if (!this.getHeader('X-Content-Type-Options')) {
    this.setHeader('X-Content-Type-Options', 'nosniff');
  }
  
  if (!this.getHeader('X-Frame-Options')) {
    this.setHeader('X-Frame-Options', 'DENY');
  }
}

// Usage in Express.js middleware
function securityMiddleware(req, res, next) {
  onHeaders(res, setDefaultHeaders);
  next();
}

Error Handling

The function throws TypeError in the following cases:

  • When the res parameter is missing or falsy
  • When the listener parameter is not a function
// These will throw TypeError
onHeaders(); // Missing res argument
onHeaders(res); // Missing listener argument  
onHeaders(res, 'not a function'); // Invalid listener type

Types

/**
 * Node.js HTTP ServerResponse object
 * @typedef {object} ServerResponse
 * @property {function} setHeader - Set a single header value
 * @property {function} getHeader - Get a header value
 * @property {function} removeHeader - Remove a header
 * @property {function} writeHead - Write the response head
 * @property {number} statusCode - HTTP status code
 * @property {function} end - End the response
 * @property {function} write - Write response data
 */

/**
 * Header listener callback function
 * @callback HeaderListener
 * @this {ServerResponse} The HTTP response object bound as context
 */

Node.js Compatibility

  • Minimum Node.js Version: 0.8
  • Compatible with: All modern Node.js versions
  • HTTP Framework Support: Works with native http module, Express.js, and other Node.js HTTP frameworks
  • Response Object: Works with standard Node.js ServerResponse instances