npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

rpc-reflector

v3.0.1

Published

Call methods on an object over RPC

Downloads

1,807

Readme

rpc-reflector

Node.js CI Coverage Status standard-readme compliant

Call methods on any object over RPC with minimal fuss.

Create a "mirror" of an object on the server in the client. You can call any methods on the server object by calling the same method name on the client object. You can also subscribe to events on the client as if you were subscribing to events on the original API. Synchronous methods on the server object become asynchronous methods on the client-side. Properties on the server object become asynchronous getter methods on the client, e.g. for a server object { foo: 'bar' } the property foo can be read on the client via await clientApi.foo().

Unlike other RPC libraries, this does not require any boilerplate to define methods that are available over RPC. All methods and properties on the server object are "reflected" in client API automatically. Any method called on the client object will return a Promise, but methods that are not defined on the server will throw with a ReferenceError.

Table of Contents

Background

Most RPC libraries I could find require a lot of boilerplate to define the methods that are available over RPC. I wanted an easy way for an API on the server to be used from a client in exactly the same way as it is on the server, without needing to setup any RPC methods. Under-the-hood this uses a Proxy object.

Install

npm install rpc-reflector

Usage

import { createClient, createServer } from 'rpc-reflector'
import { MessagePortPair } from '../test/helpers.js'

const myApi = {
  syncMethod: () => 'result1',
  asyncMethod: () =>
    new Promise((resolve) => {
      setTimeout(() => resolve('result2'), 200)
    }),
}

const { port1: serverPort, port2: clientPort } = new MessagePortPair()

const { close } = createServer(myApi, serverPort)

const myApiOnClient =
  /** @type {import('../index.js').ClientApi<typeof myApi>} */ createClient(
    clientPort,
  )

;(async () => {
  const result1 = await myApiOnClient.syncMethod()
  const result2 = await myApiOnClient.asyncMethod()
  console.log(result1) // 'result1'
  console.log(result2) // 'result2'
  close()
})()

API

const { close } = createServer(api, channel, [options])

api can be any object with any properties, methods and events that you want reflected in the client API.

channel can be a browser MessagePort, a Node Worker MessagePort or a MessagePort-like object that defines a postMessage() method and implements an EventEmitter that emits an event named 'message'.

If channel is a MessagePort you will need to manually call port.start() to start sending messages queued in the port.

options: an optional object with the following properties:

  • logger: An instance of Pino Logger or a compatible logger. If not provided, no logging will be done.
  • onRequestHook: (request: MsgRequestObj, next: (request: MsgRequestObj) => Promise<any>) => void Optional hook to observe and modify a request and its metadata, and to await the response.

close() is used to remove event listeners from the channel. It will not close or destroy the MessagePort used as the channel.

const clientApi = createClient(channel, [options])

channel: see above for createServer()

options: an optional object with the following properties:

  • logger: An instance of Pino Logger or a compatible logger. If not provided, no logging will be done.
  • onRequestHook: (request: Omit<MsgRequestObj, 'metadata'>, next: (request: MsgRequestObj) => Promise<any>) => void Optional hook to observe and modify a request and its metadata, and to await the response.
  • timeout: Optional timeout in milliseconds for requests. Default 5000ms. Note that any code that takes longer than timeout will also trigger it. Use it with caution to catch timeouts in your message channel if you know your API methods will not take longer than the timeout to respond.

Returns clientApi which can be called with any method on the api passed to createServer(). Events on api can be subscribed to via clientApi.on(eventName, handler) on the client. Properties/fields on the server api can be access by calling a method with the same name on the client API, e.g. to access the property api.myProp, on the client call await clientApi.myProp().

When using Typescript, you can pass the type of the server API as a generic e.g.

const clientApi = createClient<ServerApi>(channel)

The returned clientApi will be correctly typed, with synchronous functions converted to synchronous.

createClient.close(clientApi)

The static method close() will remove all event listeners from the channel used to create the client. It will not close or destroy the MessagePort or Stream used as the channel.

Maintainers

@gmaclennan

Contributing

PRs accepted.

Small note: If editing the README, please conform to the standard-readme specification.

License

MIT © 2020 Gregor MacLennan