{"id":11437,"library":"node-media-server","title":"Node.js Media Server","description":"Node-Media-Server is an open-source, high-performance, and low-latency live streaming server built with Node.js. The current stable version is 4.2.4. It focuses on providing a robust platform for RTMP (Real-Time Messaging Protocol), HTTP-FLV, and WS-FLV streaming, with enhanced support for modern codecs like HEVC, VP9, and AV1 in its v4 release. This version introduced a comprehensive REST API for management, JWT-based authentication, real-time monitoring, and session management, making it suitable for modern streaming applications. It differentiates itself from alternatives like Nginx RTMP or enterprise solutions by being a Node.js-native, extensible, and lightweight solution ideal for rapid development and integration into JavaScript ecosystems. While it doesn't specify a fixed release cadence, the project shows active development and regular updates.","status":"active","version":"4.2.4","language":"javascript","source_language":"en","source_url":"https://github.com/illuspas/Node-Media-Server","tags":["javascript","rtmp","flv","livestream","server"],"install":[{"cmd":"npm install node-media-server","lang":"bash","label":"npm"},{"cmd":"yarn add node-media-server","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-media-server","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"NodeMediaServer is the default export for programmatic usage in ESM contexts. Direct named imports will typically fail as it's a CommonJS module providing a default export. For CJS projects, `const NodeMediaServer = require('node-media-server');` is correct.","wrong":"import { NodeMediaServer } from 'node-media-server';","symbol":"NodeMediaServer","correct":"import NodeMediaServer from 'node-media-server';"},{"note":"For TypeScript users, the `Config` interface defines the structure for the server configuration object. It should be imported as a type, not a runtime value.","wrong":"import { Config } from 'node-media-server';","symbol":"Config","correct":"import type { Config } from 'node-media-server';"},{"note":"While event names are strings, for advanced TypeScript usage, types related to NMS events (like `NmsEvent` or event handler signatures) might be declared in the type definitions and used for strong typing event callbacks. Check the `@types/node-media-server` package for specific event type exports.","wrong":"import { NmsEvent } from 'node-media-server';","symbol":"NmsEvent","correct":"import type { NmsEvent } from 'node-media-server';"}],"quickstart":{"code":"import NodeMediaServer from 'node-media-server';\nimport * as fs from 'fs';\n\n// Ensure media and html directories exist for recording and static files\nconst mediaRoot = './media';\nconst recordPath = `${mediaRoot}/record`;\nconst htmlRoot = './html';\n\nif (!fs.existsSync(mediaRoot)) fs.mkdirSync(mediaRoot);\nif (!fs.existsSync(recordPath)) fs.mkdirSync(recordPath, { recursive: true });\nif (!fs.existsSync(htmlRoot)) fs.mkdirSync(htmlRoot);\n// Create a dummy index.html for static server to function\nif (!fs.existsSync(`${htmlRoot}/index.html`)) {\n  fs.writeFileSync(`${htmlRoot}/index.html`, '<h1>Node-Media-Server Static Content</h1><p>This is a placeholder page.</p>');\n}\n\nconst config = {\n  rtmp: {\n    port: 1935,\n    chunk_size: 60000,\n    gop_cache: true,\n    ping: 30,\n    ping_timeout: 60\n  },\n  http: {\n    port: 8000,\n    mediaroot: mediaRoot, // Directory for recorded files or static content\n    allow_origin: '*',\n    api: true, // Enable REST API\n    api_user: process.env.NMS_API_USER ?? 'admin',\n    api_pass: process.env.NMS_API_PASS ?? 's3cr3tP@ssw0rd'\n  },\n  auth: {\n    play: false,\n    publish: false,\n    secret: process.env.NMS_JWT_SECRET ?? 'superSecretKey!HighlySecure!ChangeMe!',\n    jwt: {\n      expiresIn: '1h',\n      algorithm: 'HS256',\n      users: [\n        {\n          username: process.env.NMS_ADMIN_USERNAME ?? 'admin',\n          password: process.env.NMS_ADMIN_PASSWORD ?? 'p@ssw0rdF0rAdm1n' // IMPORTANT: Hash this in production!\n        }\n      ]\n    }\n  },\n  record: {\n    path: recordPath,\n    append_file: true // Append to existing file if stream restarts\n  },\n  static: {\n    router: '/static',\n    root: htmlRoot\n  }\n};\n\nconst nms = new NodeMediaServer(config);\n\nnms.on('postPublish', (id, StreamPath, args) => {\n  console.log(`[NodeEvent on postPublish] Stream started: ${StreamPath}`);\n  // Example: Log stream details or integrate with other services\n});\n\nnms.on('doneConnect', (id, args) => {\n  console.log(`[NodeEvent on doneConnect] Client disconnected: ${id}`);\n});\n\ntry {\n  nms.run();\n  console.log('Node-Media-Server is running.');\n  console.log(`RTMP server listening on port ${config.rtmp.port}`);\n  console.log(`HTTP server with API listening on port ${config.http.port}`);\n  console.log('Access static files at /static');\n  console.log('Publish stream via RTMP, e.g., rtmp://localhost:1935/live/streamkey');\n  console.log('Play stream via HTTP-FLV, e.g., http://localhost:8000/live/streamkey.flv');\n} catch (error) {\n  console.error('Failed to start Node-Media-Server:', error);\n}","lang":"typescript","description":"This quickstart sets up a Node-Media-Server instance with RTMP and HTTP-FLV streaming, a REST API with JWT authentication, static file serving, and stream recording. It also includes basic event logging and environment variable usage for sensitive configuration."},"warnings":[{"fix":"Review the v4 documentation (or source code) thoroughly and re-configure your server from scratch, adapting to the new API and features. Do not attempt a direct configuration migration.","message":"Node-Media-Server v4 is a major breaking change and is incompatible with v2. Direct upgrades between these major versions are not supported, and configurations, particularly for extensions, must be rewritten.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Re-evaluate your streaming setup if you were using the `cn_cdn` extension for H.265. Version 4 focuses on native HEVC, VP9, AV1 support, so adjust your encoding and client-side playback accordingly.","message":"Version 4 of Node-Media-Server is no longer compatible with the `cn_cdn` extension ID `flv_265` standard. Projects relying on this specific extension will require significant adjustments or alternative solutions.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update all client-side players to use modern HTML5-based solutions (e.g., flv.js for HTTP-FLV, or other players supporting HLS/DASH) that do not rely on Flash Player for RTMP.","message":"Node-Media-Server v4 has removed compatibility with Flash Player's RTMP protocol. Legacy Flash-based clients will no longer be able to connect and stream.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"While later `4.2.x` versions seem to have resolved this, if encountering `nms.on is not a function`, ensure you are on the latest stable `4.x` release or consult the official GitHub issues for workarounds or the correct event subscription mechanism for your specific `4.x` patch version. The provided quickstart assumes `nms.on` works in `4.2.4`.","message":"The `nms.on()` event handling method, which was standard in v2.x, appears to be non-existent or broken in early v4.x versions. This can affect custom logic tied to server events.","severity":"gotcha","affected_versions":"4.0.x"},{"fix":"Always override the default `auth.secret` and the `auth.jwt.users` credentials in your `config.json` or programmatic configuration using strong, unique values, ideally loaded from environment variables (e.g., `process.env.NMS_JWT_SECRET`).","message":"The default JWT `secret` (`nodemedia2017privatekey`) and `admin` API credentials are weak and should be changed immediately in production environments to prevent unauthorized access.","severity":"gotcha","affected_versions":">=4.2.0"},{"fix":"Ensure your Node.js environment is updated to version 18.0.0 or later. Use `node -v` to check your current version and `nvm` or your package manager to update.","message":"Node-Media-Server requires Node.js version 18.0.0 or higher. Running it on older Node.js versions may lead to unexpected errors or instability.","severity":"gotcha","affected_versions":"<18.0.0 (Node.js)"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change the `rtmp.port` or `http.port` in your `config` object to an unused port, or terminate the process currently occupying the desired port. Use `lsof -i :1935` (Linux/macOS) or `netstat -ano | findstr :1935` (Windows) to identify the conflicting process.","cause":"Another process is already using the RTMP port (default 1935) or HTTP port (default 8000), preventing Node-Media-Server from binding to it.","error":"Error: listen EADDRINUSE: address already in use :::1935"},{"fix":"For CommonJS, use `const NodeMediaServer = require('node-media-server');`. For ESM, use `import NodeMediaServer from 'node-media-server';` as `node-media-server` is primarily a CommonJS module with a default export.","cause":"This typically occurs in a CommonJS (`require`) environment when attempting to import `NodeMediaServer` as a named export (`{ NodeMediaServer }`) or in an ESM environment where a default import is expected for a CJS module.","error":"TypeError: NodeMediaServer is not a constructor"},{"fix":"First, ensure `http.api: true` is set in your configuration. Authenticate by making a `POST /api/v1/login` request with correct `username` and `password` to obtain a JWT token. Include this token in subsequent API requests via the `Authorization: Bearer YOUR_JWT_TOKEN` header. Verify that the `auth.jwt.users` credentials in your server config match your login attempt.","cause":"You are attempting to access a REST API endpoint without a valid JWT token, or the token is expired/malformed, or the configured API username/password for JWT generation is incorrect.","error":"HTTP 401 Unauthorized for API endpoints"},{"fix":"Update your `node-media-server` package to the latest stable `4.x` version (e.g., `4.2.4`) where this issue is generally resolved. If the problem persists, consult the project's GitHub issues for any specific guidance related to your patch version.","cause":"This error specifically occurs in early v4.x versions (e.g., v4.0.7) where the `nms.on` event listener method was temporarily unavailable or broken, unlike in v2.x.","error":"Cannot read properties of undefined (reading 'on') for nms.on()"}],"ecosystem":"npm"}