{"id":17653,"library":"flamegraph-middleware","title":"Flamegraph Profiling Middleware for Node.js","description":"Flamegraph Middleware provides an HTTP interface for on-demand CPU and heap profiling of Node.js applications, visualizing the results as interactive flamegraphs directly in the browser. It is currently at stable version 1.0.0 and designed to be framework-agnostic, working seamlessly with native `http` servers, Express, Fastify, and other HTTP frameworks. Key differentiators include its non-blocking background profiling, dual CPU and heap profiling capabilities, and temporary in-memory storage of profiles with automatic expiration. This tool is invaluable for identifying performance bottlenecks and memory leaks in production or development environments, offering a user-friendly WebGL-powered visualization for deep analysis of execution paths and memory allocation patterns. The package emphasizes ease of integration and real-time insights.","status":"active","version":"1.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/qard/flamegraph-middleware","tags":["javascript","profiling","flamegraph","pprof","middleware","performance","cpu","heap","memory"],"install":[{"cmd":"npm install flamegraph-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add flamegraph-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add flamegraph-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for integrating flamegraph-middleware with Fastify applications as a standard HTTP middleware.","package":"@fastify/middie","optional":true},{"reason":"Optional dependency for structured logging within the middleware, if a custom pino logger is provided.","package":"pino","optional":true}],"imports":[{"note":"This package is ESM-only and requires Node.js >=18.0.0. CommonJS `require` syntax will result in an error. The default export is not the middleware function itself, but the factory function.","wrong":"const createFlamegraphMiddleware = require('flamegraph-middleware')","symbol":"createFlamegraphMiddleware","correct":"import { createFlamegraphMiddleware } from 'flamegraph-middleware'"},{"note":"Import types for TypeScript development to ensure correct configuration options are used when calling `createFlamegraphMiddleware`.","symbol":"FlamegraphMiddlewareFactoryOptions","correct":"import { createFlamegraphMiddleware, type FlamegraphMiddlewareFactoryOptions } from 'flamegraph-middleware'"},{"note":"When using `flamegraph-middleware`, it's generally expected to be in an ESM context, thus `import http from 'http'` is the standard way to get Node's native HTTP module.","wrong":"const http = require('http')","symbol":"http","correct":"import http from 'http'"}],"quickstart":{"code":"import express from 'express';\nimport { createFlamegraphMiddleware } from 'flamegraph-middleware';\n\nconst app = express();\n\n// Configure and use the flamegraph middleware\n// Access profiles at http://localhost:3000/flamegraph\napp.use(createFlamegraphMiddleware({\n  basePath: '/flamegraph',\n  defaultDuration: 10000, // 10 seconds\n  maxDuration: 60000,   // Max 1 minute profile\n  profileTTL: 300000    // Profiles expire after 5 minutes\n}));\n\napp.get('/', (req, res) => {\n  res.send('Hello World! Access /flamegraph to start profiling.');\n});\n\napp.get('/slow', (req, res) => {\n  let sum = 0;\n  for (let i = 0; i < 1e7; i++) {\n    sum += Math.sqrt(i);\n  }\n  res.send(`Computed sum: ${sum}. Profile this endpoint with /flamegraph?duration=5000`);\n});\n\nconst PORT = 3000;\napp.listen(PORT, () => {\n  console.log(`Express server running at http://localhost:${PORT}`);\n  console.log(`Start a profile: http://localhost:${PORT}/flamegraph?duration=5000`);\n  console.log(`View results after profiling: http://localhost:${PORT}/flamegraph`);\n});","lang":"typescript","description":"Demonstrates integrating `flamegraph-middleware` into an Express application, showing how to configure it, start a CPU/heap profile via HTTP, and access the interactive flamegraph visualizations."},"warnings":[{"fix":"Ensure your project is configured for ESM (`\"type\": \"module\"` in `package.json`) and you are running Node.js 18+ or higher. Use `import` statements exclusively.","message":"This package is ESM-only and explicitly requires Node.js version 18.0.0 or higher. Attempting to use it with CommonJS `require()` or older Node.js versions will result in runtime errors.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Register `@fastify/middie` before using `flamegraph-middleware`:\n`await fastify.register(middie); fastify.use(createFlamegraphMiddleware(...))`","message":"When integrating with Fastify, the `@fastify/middie` plugin is required to use `flamegraph-middleware` as a standard HTTP middleware. Failure to register `middie` first will prevent the middleware from being properly applied.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully manage `defaultDuration` and `maxDuration` in production environments. Request profiles with specific durations (e.g., `?duration=5000`) and avoid excessively long profiles.","message":"The default duration for profiling is 10 seconds, and the maximum allowed duration is 60 seconds. Profiles exceeding `maxDuration` via query parameter will be capped, and very long profiles can consume significant CPU and memory resources on the target server.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Adjust `maxProfiles` and `profileTTL` configuration options based on your monitoring needs and available memory. Download or view profiles promptly after completion if long-term storage is required.","message":"Profiles are stored temporarily in memory and automatically expire. If the `maxProfiles` limit is reached, older profiles will be evicted. Profiles also expire after `profileTTL` milliseconds.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Switch your project to ESM by adding `\"type\": \"module\"` to your `package.json` and using `import { createFlamegraphMiddleware } from 'flamegraph-middleware'`.","cause":"Attempting to `require()` `flamegraph-middleware` in a CommonJS context.","error":"ERR_REQUIRE_ESM: Must use import to load ES Module:"},{"fix":"Ensure you are using the *result* of the factory function. For Express/Fastify, it should be `app.use(createFlamegraphMiddleware())` or `app.use(flamegraphMiddlewareInstance)`.","cause":"Incorrectly calling `app.use(flamegraph)` directly when `flamegraph` is the result of `createFlamegraphMiddleware()` (which is a factory).","error":"Error: Middleware is not a function"},{"fix":"Replace `require('module')` with `import module from 'module'` or `import { namedExport } from 'module'` for all dependencies.","cause":"Using `require()` inside an ES module (where `\"type\": \"module\"` is set in `package.json`).","error":"ReferenceError: require is not defined in ES module scope"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}