{"id":13365,"library":"jayson","title":"Jayson JSON-RPC Server and Client","description":"Jayson is a comprehensive JavaScript library providing both server and client implementations for the JSON-RPC 2.0 and 1.0 specifications. It enables developers to build robust remote procedure call systems over HTTP, HTTPS, TCP, TLS, and WebSockets connections, primarily targeting Node.js environments. The current stable version is 4.3.0. The project maintains an active development pace with ongoing bug fixes and feature enhancements, though major version releases are not on a fixed cadence. Key differentiators include its support for simultaneous server interfaces, relaying requests, flexible method routing, transparent serialization using revivers/replacers, and first-class Promises support, making it suitable for complex distributed systems and microservices architectures. It also ships with full TypeScript type definitions since v2.1.0.","status":"active","version":"4.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/tedeh/jayson","tags":["javascript","jsonrpc","json-rpc","rpc","json","jsonrpc-2.0","jsonrpc-1.0","middleware","connect","typescript"],"install":[{"cmd":"npm install jayson","lang":"bash","label":"npm"},{"cmd":"yarn add jayson","lang":"bash","label":"yarn"},{"cmd":"pnpm add jayson","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Both CommonJS `require` and ESM `import` are supported for Node.js. For TypeScript or modern Node.js projects, ESM import is generally preferred. Jayson v4 ships with comprehensive type declarations.","wrong":"const jayson = require('jayson');","symbol":"jayson","correct":"import * as jayson from 'jayson';"},{"note":"The main Server class is available as a named export. Direct import `import { Server } from 'jayson';` is recommended over accessing properties of the default import for clarity and tree-shaking benefits in ESM contexts.","wrong":"const Server = require('jayson').Server;","symbol":"Server","correct":"import { Server } from 'jayson';"},{"note":"Client constructors like `http`, `tcp`, `https`, `tls`, and `websocket` are static methods on the `Client` class, not direct named exports. Browser usage requires `require('jayson/lib/client/browser')` and a custom transport function.","wrong":"import { http } from 'jayson/lib/client/http';","symbol":"Client.http","correct":"import { Client } from 'jayson';\nconst httpClient = Client.http({ port: 3000 });"}],"quickstart":{"code":"const jayson = require('jayson'); // Or import * as jayson from 'jayson';\nconst http = require('http');\n\n// --- Server Setup ---\n// Create a JSON-RPC server with 'add' and 'subtract' methods\nconst server = new jayson.Server({\n  add: function(args, callback) {\n    if (args.length !== 2 || typeof args[0] !== 'number' || typeof args[1] !== 'number') {\n      return callback({ code: -32602, message: 'Invalid params: two numbers expected' });\n    }\n    callback(null, args[0] + args[1]);\n  },\n  subtract: async function(args) {\n    if (args.length !== 2 || typeof args[0] !== 'number' || typeof args[1] !== 'number') {\n      throw { code: -32602, message: 'Invalid params: two numbers expected' };\n    }\n    return args[0] - args[1];\n  }\n});\n\n// Create and start the HTTP server\nconst httpServer = http.createServer(server.http());\nhttpServer.listen(3000, () => {\n  console.log('JSON-RPC server listening on port 3000');\n\n  // --- Client Usage ---\n  // Create an HTTP client pointing to the server\n  const client = jayson.Client.http({\n    port: 3000,\n    hostname: 'localhost'\n  });\n\n  // Invoke \"add\" with callback\n  client.request('add', [5, 3], function(err, response) {\n    if (err) {\n      console.error('Error from \"add\" call:', err);\n      httpServer.close(() => process.exit(1));\n      return;\n    }\n    console.log('Result from \"add\":', response.result); // Expected: 8\n\n    // Invoke \"subtract\" with promises\n    client.request('subtract', [10, 4])\n      .then(response => {\n        console.log('Result from \"subtract\":', response.result); // Expected: 6\n        httpServer.close(() => process.exit(0));\n      })\n      .catch(err => {\n        console.error('Error from \"subtract\" call:', err);\n        httpServer.close(() => process.exit(1));\n      });\n  });\n});","lang":"javascript","description":"Demonstrates setting up a basic Jayson HTTP JSON-RPC server with both callback-based and promise-based methods, and then invoking these methods from a Jayson HTTP client."},"warnings":[{"fix":"Review your application for direct or indirect dependencies on `lodash` when interacting with Jayson methods and adjust data structures or serialization logic as needed. Ensure objects and arrays passed to Jayson conform to standard JavaScript types.","message":"Jayson v4 introduced significant API changes, notably removing the `lodash` dependency to halve bundle size. This might lead to minor incompatibilities if older code relied on `lodash` specific object/array types being passed directly to Jayson methods.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update server method signatures to ensure all JSON-RPC parameters are accessed from the first argument. If you previously used `collect` functionality, you may need to implement custom parameter collection logic.","message":"In Jayson v3.0.0, the `collect` option was removed from `jayson.Server` and `jayson.Method`. Additionally, JSON-RPC parameters to handlers are now always provided in the first argument, which may break existing server method implementations.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always construct JSON-RPC compliant error objects in your server methods. When using the callback signature `callback(error, result)`, ensure `error` is a structured object, not just an `Error` instance. For promise-based methods, throw an object matching the JSON-RPC error structure.","message":"Jayson strictly adheres to the JSON-RPC specification regarding error responses. Custom server methods must return errors in the specified JSON-RPC error object format (e.g., `{ code: -32000, message: 'Custom error', data: { details: '...' } }`) to be correctly parsed by clients. Returning plain `Error` objects might lead to generic 'Internal error' messages.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure CORS headers on your Jayson HTTP server (e.g., `server.http({ cors: true, headers: { /* ... */ } })`) or ensure client and server are on the same origin. For browser clients, you might need to use `require('jayson/lib/client/browser')` with a custom transport.","message":"When using Jayson in a browser environment, be aware of browser-specific limitations such as Cross-Origin Resource Sharing (CORS) for HTTP clients or WebSocket security policies. Proper server-side CORS configuration is often required for cross-origin requests.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Migrate server method implementations and client request calls to use Promises (`async/await` or `.then/.catch`) where appropriate, leveraging the built-in Promise support for cleaner asynchronous code. Note that JSON-RPC errors typically do not reject promises; they are returned in the response object.","message":"While Jayson continues to support callback-based asynchronous operations, the library has added robust Promise support since v2.0.0, and further enhanced it in v3.3.3 for browser clients. New development should favor Promise-based APIs for improved async control flow and error handling.","severity":"deprecated","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the Jayson server (`server.http().listen(...)` or `server.tcp().listen(...)`) is active and reachable from the client's host and port. Check firewall rules, network configurations, and that the server process is indeed running.","cause":"The Jayson server is not running or is not listening on the specified network interface (IP address and port) that the client is trying to connect to.","error":"Error: connect ECONNREFUSED 127.0.0.1:3000"},{"fix":"Verify that the client is sending a well-formed JSON-RPC request body, including all required fields (`jsonrpc`, `method`, `params`, `id`). Use a debugging tool or a simple `curl` command to send a minimal valid request to the server to isolate the issue.","cause":"The incoming client request does not conform to the JSON-RPC 1.0 or 2.0 specification. Common issues include missing the `jsonrpc` field (for v2.0), an invalid `id`, or malformed JSON payload.","error":"JSON-RPC Error: Invalid Request (-32600)"},{"fix":"Check the method name in the client's `client.request('methodName', ...)` call. Ensure it exactly matches a method name provided in the server's method object (`new jayson.Server({ methodName: function(...) { ... } })`). Case sensitivity matters.","cause":"The client requested a method name that has not been registered or defined on the Jayson server's method map.","error":"JSON-RPC Error: Method not found (-32601)"},{"fix":"Examine the `args` parameter in your server method's definition and compare it to the `params` sent by the client. Ensure the types, number, and structure of arguments match, paying close attention to whether the method expects positional parameters (an array) or named parameters (an object). Add validation to your server methods if input varies.","cause":"The parameters (`params`) provided by the client do not match what the server method expects (e.g., wrong data type, incorrect number of arguments, or unexpected structure for named parameters).","error":"JSON-RPC Error: Invalid params (-32602)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}