brillout
brillout

Reputation: 7474

Get HTTP headers/body from async hook HTTPINCOMINGMESSAGE

I'm trying to get the HTTP headers and the HTTP body from the IncomingMessage instance provided by the async hook HTTPINCOMINGMESSAGE:

import asyncHooks = require("async_hooks");
import { IncomingMessage } from "http";

asyncHooks.createHook({
  init: (
    asyncId: number,
    type: string,
    triggerAsyncId: number,
    req: IncomingMessage
  ) => {
    if (type !== "HTTPINCOMINGMESSAGE") return;

    // Where are the HTTP headers?
    console.log(req.headers); // prints `undefined`

    // How do I get the HTTP body?
    console.log(req.on); // prints `undefined`

    // Yet, `req` is an `IncomingMessage`, the same than following `req`:
    //
    //   const http = require('http');
    //   http.createServer((req, res) => {
    //     // The HTTP request headers are available here!
    //     console.log(req.headers);
    //     // `req` is an `IncomingMessage` as well
    //     console.log(req.constructor===IncomingMessage); // prints `true`
    //   });
    //
    console.log(req.constructor===IncomingMessage); // prints `true`
  },
})
.enable();

I've digged into the Node.js source code, but no luck. I can't find the code that populates req.headers, nor the code that creates the HTTP body stream.

Edit

The overarching goal is to enable Wildcard API to provide a context:

import { context } from '@wildcard-api/server';

// Wildcard saves a cookie on behaf of the Wildcard user, and exposes
// the value saved in the cookie over an ES6 proxy `context`.

function called_somewhere_within_an_http_request_lifecycle() {
  // Wildcard uses Async Hooks to be able to know the HTTP request associated
  // with the following `context.userName` ES6 proxy getter call, and therefore
  // can provide the value `userName` saved in the cookie of the HTTP request.
  console.log(context.userName);
}

Upvotes: 0

Views: 448

Answers (1)

Paul Rumkin
Paul Rumkin

Reputation: 6883

Async hooks should not be used to modify program behavior. This API has been created to track async resources, e.g. to measure performance. Trying to modify the program in that way leads to undefined behavior and unpredictable errors.

You can monkey-patch NodeJS' HTTP library to do so, but I strongly suggest you to avoid it.

Upvotes: -1

Related Questions