HTTP Post Message

raw JSON →
0.3.0 verified Thu Apr 23 auth: no javascript maintenance

The `http-post-message` package provides a generic messaging component to facilitate HTTP-style communication over the `window.postMessage` API. It abstracts the raw `postMessage` mechanics into familiar HTTP methods like `get`, `post`, `put`, `patch`, and `delete`, allowing developers to send structured requests and receive responses with HTTP semantics (e.g., status codes, headers). The current stable version is `0.3.0`. It does not implement the underlying `postMessage` transport itself but requires an external implementation of an `IPostMessage` interface, most commonly fulfilled by the `window-post-message-proxy` library, which Microsoft also maintains. Its key differentiator is bringing a robust, HTTP-like request/response pattern to cross-window and cross-iframe communication, simplifying complex messaging scenarios.

error TypeError: Cannot read properties of undefined (reading 'postMessage')
cause `HttpPostMessage` was instantiated without a valid `IPostMessage` implementation, or the provided object does not have a `postMessage` method.
fix
Ensure an object implementing the IPostMessage interface (e.g., an instance of WindowPostMessageProxy) is passed as the first argument to the HttpPostMessage constructor.
error Promise never resolves for http-post-message request.
cause The `window-post-message-proxy` (or equivalent) on the receiving end is not correctly configured to track messages or is not sending back correlation IDs required by `http-post-message`.
fix
Verify that window-post-message-proxy on both sending and receiving sides uses HttpPostMessage.addTrackingProperties and HttpPostMessage.getTrackingProperties in its processTrackingProperties configuration.
error Error: Request failed with status code 500 (or other HTTP error code), but the underlying message was not an error.
cause The `isErrorMessage` configuration in `window-post-message-proxy` is not correctly identifying error responses from the receiving frame.
fix
Ensure window-post-message-proxy is configured with isErrorMessage: HttpPostMessage.isErrorMessage during its instantiation to properly classify incoming messages as errors based on HTTP semantics.
gotcha This package solely provides the HTTP-style abstraction layer and does NOT implement the actual `window.postMessage` transport. It critically depends on an external library (like `window-post-message-proxy`) to handle the sending and receiving of messages.
fix Ensure you have `window-post-message-proxy` installed and correctly configured and pass its instance to the `HttpPostMessage` constructor.
breaking The package is still in a `0.x.x` version range. This implies that the API might not be stable and could introduce breaking changes in minor versions without adhering to strict semver for major API shifts.
fix Pin the exact version (`npm install --save-exact http-post-message@0.3.0`) or thoroughly test updates before deploying to production.
gotcha Correct configuration of `window-post-message-proxy` is essential for `http-post-message` to interpret responses correctly. Specifically, `processTrackingProperties` and `isErrorMessage` callbacks must be set using `HttpPostMessage`'s static methods.
fix When initializing `WindowPostMessageProxy`, use `hpm.HttpPostMessage.addTrackingProperties`, `hpm.HttpPostMessage.getTrackingProperties`, and `hpm.HttpPostMessage.isErrorMessage` as shown in the package's documentation to ensure proper message tracking and error handling.
npm install http-post-message
yarn add http-post-message
pnpm add http-post-message

Demonstrates how to instantiate `HttpPostMessage` with a basic proxy and perform `get` and `post` requests, illustrating the HTTP-style API.

import { HttpPostMessage } from 'http-post-message';
import { WindowPostMessageProxy } from 'window-post-message-proxy';

// 1. Set up a mock postMessage proxy (for demonstration)
// In a real app, you would use WindowPostMessageProxy configured correctly.
const stubPostMessageProxy = {
  postMessage: (message: any, targetOrigin?: string, targetWindow?: Window) => {
    console.log('Sending message:', message);
    // Simulate receiving a response after a delay
    return Promise.resolve({
      id: message.id, // Important for correlation
      data: { status: 200, body: `Echo: ${JSON.stringify(message.data)}` },
      error: null
    });
  },
};

// 2. Instantiate HttpPostMessage with the proxy
const httpPostMessage = new HttpPostMessage(stubPostMessageProxy);

// 3. Make an HTTP-style GET request
async function runExample() {
  try {
    console.log('Making GET request to target/path...');
    const response = await httpPostMessage.get('target/path', { headers: { 'X-Custom-Header': 'value' } });
    console.log('Received response:', response.body);

    // 4. Make an HTTP-style POST request
    console.log('\nMaking POST request to /api/data...');
    const postResponse = await httpPostMessage.post('/api/data', { item: 'new item' });
    console.log('Received POST response:', postResponse.body);

  } catch (error) {
    console.error('Request failed:', error);
  }
}

runExample();

/* Example output (simplified):
Sending message: { id: '...', url: 'target/path', method: 'GET', data: {}, headers: { 'X-Custom-Header': 'value' } }
Received response: Echo: {}

Making POST request to /api/data...
Sending message: { id: '...', url: '/api/data', method: 'POST', data: { item: 'new item' }, headers: {} }
Received POST response: Echo: {"item":"new item"}
*/