Registry / http-networking / jayson

jayson

JSON →
library0.0.2jsnpmunverified

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.

npm install jayson
INSTALL
IMPORT
SIG · JAYSON
J
jayson
http-networkingjavascriptv0.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

jayson
import * as jayson from 'jayson';
const jayson = require('jayson');
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.
Server
import { Server } from 'jayson';
const Server = require('jayson').Server;
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.
Client.http
import { Client } from 'jayson'; const httpClient = Client.http({ port: 3000 });
import { http } from 'jayson/lib/client/http';
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.

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.

const jayson = require('jayson'); // Or import * as jayson from 'jayson'; const http = require('http'); // --- Server Setup --- // Create a JSON-RPC server with 'add' and 'subtract' methods const server = new jayson.Server({ add: function(args, callback) { if (args.length !== 2 || typeof args[0] !== 'number' || typeof args[1] !== 'number') { return callback({ code: -32602, message: 'Invalid params: two numbers expected' }); } callback(null, args[0] + args[1]); }, subtract: async function(args) { if (args.length !== 2 || typeof args[0] !== 'number' || typeof args[1] !== 'number') { throw { code: -32602, message: 'Invalid params: two numbers expected' }; } return args[0] - args[1]; } }); // Create and start the HTTP server const httpServer = http.createServer(server.http()); httpServer.listen(3000, () => { console.log('JSON-RPC server listening on port 3000'); // --- Client Usage --- // Create an HTTP client pointing to the server const client = jayson.Client.http({ port: 3000, hostname: 'localhost' }); // Invoke "add" with callback client.request('add', [5, 3], function(err, response) { if (err) { console.error('Error from "add" call:', err); httpServer.close(() => process.exit(1)); return; } console.log('Result from "add":', response.result); // Expected: 8 // Invoke "subtract" with promises client.request('subtract', [10, 4]) .then(response => { console.log('Result from "subtract":', response.result); // Expected: 6 httpServer.close(() => process.exit(0)); }) .catch(err => { console.error('Error from "subtract" call:', err); httpServer.close(() => process.exit(1)); }); }); });
Debug
Known issues
breakingJayson 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.
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.
affects: >=4.0.0
breakingIn 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.
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.
affects: >=3.0.0
gotchaJayson 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.
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.
affects: >=1.0.0
gotchaWhen 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.
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.
affects: >=1.0.0
deprecatedWhile 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.
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.
affects: >=2.0.0
Errors
Common errors & fixes
Error: connect ECONNREFUSED 127.0.0.1:3000
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.
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.
JSON-RPC Error: Invalid Request (-32600)
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.
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.
JSON-RPC Error: Method not found (-32601)
The client requested a method name that has not been registered or defined on the Jayson server's method map.
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.
JSON-RPC Error: Invalid params (-32602)
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).
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.
Upgrade
Version history
0.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources