NPM Package Integration
Use and publish JSON-RPC tools as NPM packages for JavaScript and TypeScript projects
On this page
Overview
NPM packages provide an excellent way to distribute, use, and maintain JSON-RPC tools in JavaScript and TypeScript projects. This guide covers both using existing JSON-RPC packages and creating your own.
Whether you're building a client library, server implementation, or utilities for working with JSON-RPC, NPM offers a standardized way to share your code with the JavaScript ecosystem.
Using JSON-RPC Packages
Popular JSON-RPC NPM Packages
@jsonrpc-tools/validator
Validates JSON-RPC requests and responses against the specification
npm install @jsonrpc-tools/validator
@jsonrpc-tools/client
Client library for making JSON-RPC requests with built-in validation
npm install @jsonrpc-tools/client
@jsonrpc-tools/server
Server-side tools for handling JSON-RPC requests
npm install @jsonrpc-tools/server
@jsonrpc-tools/utils
Utility functions for working with JSON-RPC protocols
npm install @jsonrpc-tools/utils
Basic Usage Example
// Using the JSON-RPC client package
import { JsonRpcClient } from '@jsonrpc-tools/client';
// Create a client instance
const client = new JsonRpcClient({
endpoint: 'https://api.example.com/jsonrpc',
version: '2.0'
});
// Make a request
async function getUserData(userId) {
try {
const result = await client.request('user.get', { userId });
console.log('User data:', result);
return result;
} catch (error) {
console.error('Error fetching user data:', error);
throw error;
}
}
// Make a batch request
async function batchRequests() {
const batch = [
client.createRequest('user.get', { userId: 1 }),
client.createRequest('user.getPermissions', { userId: 1 })
];
const results = await client.batchRequest(batch);
console.log('Batch results:', results);
return results;
}
Publishing Your JSON-RPC Package
If you're developing JSON-RPC utilities that could benefit others, consider publishing them as NPM packages:
Package Structure
my-jsonrpc-package/
├── src/
│ ├── index.js # Main entry point
│ ├── client.js # Client implementation
│ ├── validation.js # Validation logic
│ └── utils.js # Utility functions
├── dist/ # Compiled code (created by build process)
├── tests/ # Test files
├── examples/ # Example usage
├── package.json # Package configuration
├── README.md # Documentation
├── LICENSE # License file
└── .npmignore # Files to exclude from npm package
Essential package.json Configuration
{
"name": "my-jsonrpc-package",
"version": "1.0.0",
"description": "JSON-RPC client library with advanced features",
"main": "dist/index.js",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "rollup -c",
"test": "jest",
"prepublishOnly": "npm run build && npm test"
},
"keywords": [
"json-rpc",
"api",
"client",
"jsonrpc2"
],
"author": "Your Name <[email protected]>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/yourusername/my-jsonrpc-package.git"
},
"dependencies": {
// List dependencies
},
"devDependencies": {
// List dev dependencies
}
}
Publishing Steps
- Create an NPM account if you don't have one:
npm adduser
- Build your package:
npm run build
- Test your package thoroughly:
npm test
- Update version in package.json following semantic versioning
- Publish to NPM registry:
npm publish
Note: Consider using the npm link
command to test your package locally before publishing.
TypeScript Support
TypeScript provides excellent type safety for JSON-RPC, particularly for complex parameter and result structures.
JSON-RPC Type Definitions
// types.ts
export interface JsonRpcRequest<T = any> {
jsonrpc: '2.0';
method: string;
params?: T;
id: string | number | null;
}
export interface JsonRpcResponse<T = any> {
jsonrpc: '2.0';
result?: T;
error?: JsonRpcError;
id: string | number | null;
}
export interface JsonRpcError {
code: number;
message: string;
data?: any;
}
// Method-specific parameter and result types
export interface UserGetParams {
userId: number;
}
export interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
}
TypeScript Usage Example
// client.ts
import { JsonRpcRequest, JsonRpcResponse, UserGetParams, User } from './types';
export class TypedJsonRpcClient {
private endpoint: string;
constructor(endpoint: string) {
this.endpoint = endpoint;
}
async request<P, R>(method: string, params?: P): Promise<R> {
const request: JsonRpcRequest<P> = {
jsonrpc: '2.0',
method,
params,
id: Date.now().toString()
};
const response = await fetch(this.endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request)
});
const jsonResponse: JsonRpcResponse<R> = await response.json();
if (jsonResponse.error) {
throw new Error(`JSON-RPC Error: ${jsonResponse.error.message}`);
}
return jsonResponse.result!;
}
// Type-safe method for getting user data
async getUser(params: UserGetParams): Promise<User> {
return this.request<UserGetParams, User>('user.get', params);
}
}
Example Packages
Explore these example JSON-RPC packages for inspiration: