MCPcopy Index your code
hub / github.com/Moesif/moesif-nodejs

github.com/Moesif/moesif-nodejs @v3.11.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v3.11.0 ↗ · + Follow
89 symbols 187 edges 27 files 5 documented · 6% updated 7mo agov3.11.0 · 2025-11-24★ 44
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Moesif Node.js Middleware Documentation

by Moesif, the API analytics and API monetization platform.

NPM

[![Built For][ico-built-for]][link-built-for] [![Total Downloads][ico-downloads]][link-downloads] [![Software License][ico-license]][link-license] [![Source Code][ico-source]][link-source]

Moesif Node.js middleware automatically logs incoming and outgoing API calls and sends them to Moesif for API analytics and monitoring. This middleware allows you to integrate Moesif's API analytics and API monetization features into your Node.js applications with minimal configuration.

If you're new to Moesif, see our Getting Started resources to quickly get up and running.

Notes

  • Previously, this NPM package was called moesif-express. In version 3.0, it has been renamed to moesif-nodejs to reflect support for any Node.js app.
  • The library can capture both incoming and outgoing API Calls depending on how you configure the SDK. For more information, see the examples.
  • To make sure the SDK captures request body, if you use a body parser middleware like body-parser, apply Moesif middleware after it.

Who This Middleware is For

The middleware works with REST APIs, GraphQL APIs (such as with Apollo), and more.

This SDK supports any Node.js framework including Express, Koa, and Nest.js. See the examples for more information.

Prerequisites

Before using this middleware, make sure you have the following:

Get Your Moesif Application ID

After you log into Moesif Portal, you can get your Moesif Application ID during the onboarding steps. You can always access the Application ID any time by following these steps from Moesif Portal after logging in:

  1. Select the account icon to bring up the settings menu.
  2. Select Installation or API Keys.
  3. Copy your Moesif Application ID from the Collector Application ID field. Accessing the settings menu in Moesif Portal

Install the Middleware

In your project directory, install the middleware as a project dependency:

npm install --save moesif-nodejs

Configure the Middleware

See the available configuration options to learn how to configure the middleware for your use case.

How to Use

The following step shows how to import Moesif for an example app using Express.js.

1. Import the Module

// 1. Import Modules
var express = require('express');
var app = express();
var moesif = require('moesif-nodejs');

// 2. Set the options, the only required field is applicationId.
var options = {

  applicationId: 'YOUR_MOESIF_APPLICATION_ID',

  logBody: true,

  identifyUser: function (req, res) {
    if (req.user) {
      return req.user.id;
    }
    return undefined;
  },

  getSessionToken: function (req, res) {
    return req.headers['Authorization'];
  }
};

// 3. Initialize the middleware object with options
var moesifMiddleware = moesif(options);


// 4a. Start capturing outgoing API Calls to 3rd parties like Stripe
// Skip this step if you don't want to capture outgoing API calls
moesifMiddleware.startCaptureOutgoing();

// 4b. Use the Moesif middleware to start capturing incoming API Calls
// If you have a body parser middleware, apply Moesif middleware after any body parsers.
// Skip this step if you don't want to capture incoming API calls
app.use(moesifMiddleware);

Replace YOUR_MOESIF_APPLICATION_ID with your Moesif Application ID.

If you are using babel or newer versions of Node.js, you can using more modern syntax for importing—for example, import moesif from 'moesif-nodejs'; . If you are using ECMAScript modules (ES modules), you can try the following method:

const moesifImported = await import('moesif-nodejs');
const moesif = moesifImported.default;

2. Enter Your Moesif Application ID

The middleware expects your Moesif Application ID in the applicationId key of the Moesif initialization options object.

For instructions on how to obtain your Application ID, see Get your Moesif Application ID.

You can hardcode your Moesif Application ID value in applicationId. But we highly recommend that you use a more secure option like environment variables to store your Application ID. If you set the environment variable as MOESIF_APPLICATION_ID, Moesif automatically picks it up without you having to explicitly specify it in the applicationId key.

var moesif = require('moesif-nodejs');
const http = require('http');

var options = {
  applicationId: 'YOUR_MOESIF_APPLICATION_ID',
  logBody: true,
};

var server = http.createServer(function (req, res) {
  moesif(options)(req, res, function () {
    // Callback
  });

  req.on('end', function () {

    res.write(JSON.stringify({
      message: "hello world!",
      id: 2
    }));
    res.end();
  });
});

server.listen(8080);

Replace YOUR_MOESIF_APPLICATION_ID with your Moesif Application ID.

3. Call your API

Finally, grab the URL to your API endpoint and make some HTTP requests using a tool like Postman or cURL.

Troubleshoot

For a general troubleshooting guide that can help you solve common problems, see Server Troubleshooting Guide. For troubleshooting issues with capturing outgoing API calls, see Troubleshoot Capturing Outgoing API Calls

Other troubleshooting supports:

Troubleshoot Capturing Outgoing API Calls

For instrumenting or capturing outgoing API calls, it instruments standard HTTP or HTTPs from Node.js core. However, some third party SDKS may use customized HTTP clients to make API calls, which may interfere with instrumentation.

Here are some tips:

  • Some SDKS, like the Stripe Node.js SDK, even though they have a very customized http client, lets you swap out to a more standard HTTP client like node-fetch.

``javascript import fetch from 'node-fetch'; // you may have to add bynpm install node-fetch` or yarn equivalent. import Stripe from 'stripe';

const stripeClient = Stripe('your secret key', { // basically you are using node fetch as the httpClient. httpClient: Stripe.createFetchHttpClient(fetch), }); ```

  • Turn outgoingPatch flag to true in configuration options to make an attempt to cover non-standard HTTP client usage. However, it may not cover all cases.

javascript { const moesifOptions = { // ... other options, outgoingPatch: true };

Repository Structure

.
├── app.js
├── dist/
├── eslint.config.mjs
├── images/
├── lib/
├── LICENSE
├── package.json
├── package-lock.json
├── README.md
├── test/
└── tsconfig.json

Configuration Options

Note: If you're using Koa, you can access the state object through request.state.

The following sections describe the available configuration options for this middleware. You can set these options in the Moesif initialization options object. See the example Express.js application code for an example.

logBody

Data type Default
Boolean true

Whether to log request and response body to Moesif.

identifyUser

Data type Parameters Return type
Function (req, res) String

A function that takes Express.js Request and Response objects as arguments and returns a user ID. This allows Moesif to attribute API requests to individual unique users so you can understand who is calling your API. You can use this simultaneously with identifyCompany to track both individual customers and the companies they are a part of.

var options = {
  identifyUser: function (req, res) {
    // your code here must return the user id as a string. Example Below
    return req.user ? req.user.id : undefined;
  }
}

identifyCompany

Data type Parameters Return type
Function (req, res) String

A function that takes Express.js Request and Response objects as arguments and returns a company ID. If you have a B2B business, this allows Moesif to attribute API requests to specific companies or organizations so you can understand which accounts are calling your API. You can use this simultaneously with identifyUser to track both individual customers and the companies they are a part of.

var options = {
  identifyCompany: function (req, res) {
    // your code here must return the company id as a string. Example Below
    return req.headers['X-Organization-Id']
  }
}

getSessionToken

Data type Parameters Return type
Function (req, res) String

A function that takes Express.js Request and Response objects as arguments and returns a session token such as an API key.

var options = {
  getSessionToken: function (req, res) {
    // your code here must return a string. Example Below
    return req.headers['Authorization'];
  }
}

getApiVersion

Data type Parameters Return type
Function (req, res) String

A function that takes Express.js Request and Response objects as arguments and returns a string to tag requests with a specific version of your API.

var options = {
  getApiVersion: function (req, res) {
    // your code here must return a string. Example Below
    return req.headers['X-Api-Version']
  }
}

getMetadata

Data type Parameters Return type
Function (req, res) Object

A function that takes Express.js Request and Response objects as arguments and returns an object.

This function allows you to add custom metadata that Moesif can associate with the request. The metadata must be a simple JavaScript object that can be converted to JSON.

For example, you may want to save a virtual machine instance ID, a trace ID, or a tenant ID with the request.

var options = {
  getMetadata: function (req, res) {
    // your code here:
    return {
      foo: 'custom data',
      bar: 'another custom data'
    };
  }
}

skip

Data type Parameters Return type
Function (req, res) Boolean

A function that takes Express.js Request and Response objects as arguments and returns true if you want to skip the event. Skipping an event means Moesif doesn't log the event.

The following example skips requests to the root path /:

var options = {
  skip: function (req, res) {
    // your code here must return a boolean. Example Below
    if (req.path === '/' || req.path === '/health') {
      // Skip logging traffic to root path or health probe.
      return true;
    }
    return false
  }
}

maskContent

Data type Parameters Return type
Function (MoesifEventModel) MoesifEventMode

Core symbols most depended-on inside this repo

logMessage
called by 83
lib/dataUtils.js
done
called by 42
lib/getRawBody.js
logger
called by 26
test/outgoingUnit.js
timeTookInSeconds
called by 20
lib/dataUtils.js
appendChunk
called by 8
lib/dataUtils.js
ensureToString
called by 8
lib/dataUtils.js
doesRegexConfigMatch
called by 7
lib/governanceRulesManager.js
loggerTestHelper
called by 6
test/mockserver.js

Shape

Function 89

Languages

TypeScript100%

Modules by API surface

lib/dataUtils.js21 symbols
lib/governanceRulesManager.js10 symbols
lib/index.js9 symbols
lib/getRawBody.js9 symbols
lib/ensureValidUtils.js8 symbols
lib/outgoing.js6 symbols
lib/nextjsUtils.js5 symbols
lib/formatEventDataAndSave.js5 symbols
test/mockserver.js4 symbols
lib/outgoingRecorder.js3 symbols
test/outgoingWithMoesif.js2 symbols
test/outgoingUnit.js2 symbols

For agents

$ claude mcp add moesif-nodejs \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact