nexus

Quick Start

Provide a document service in one context and call it from another.

This guide connects two JavaScript contexts and calls a shared document service. It uses a Chrome extension for a concrete transport: the background owns the service and a content script consumes it. The service contract and call pattern are the same with other adapters.

Use an existing TypeScript extension project that bundles a background service worker and a content script into its manifest. The browser must load both bundles; Nexus configures communication between them.

Install

pnpm add @nexus-js/core @nexus-js/chrome

Define A Shared Contract

Both bundles import this module. It contains the service’s TypeScript interface and its runtime identifier, the Token:

shared.ts
import { Token } from "@nexus-js/core";

export interface DocumentService {
  summarize(documentId: string): Promise<string>;
}

export const DocumentToken = new Token<DocumentService>("example:documents");

The contract describes a capability. The connection target will be chosen by the consumer, separately from the Token.

Provide The Service

Configure the background runtime and register an object implementing the contract:

background.ts
import { usingBackgroundScript } from "@nexus-js/chrome";
import { DocumentToken, type DocumentService } from "./shared";

const background = usingBackgroundScript();

const documents: DocumentService = {
  async summarize(documentId) {
    return `Summary of ${documentId}`;
  },
};

background.provide(DocumentToken, documents);

Register the provider synchronously after setup so it is included in the startup catalog. Providing services also covers class providers and services registered after startup.

Connect And Call

Configure the content-script runtime, acquire a connection, and get the service:

content.ts
import { chromeTarget, usingContentScript } from "@nexus-js/chrome";
import { DocumentToken } from "./shared";

const content = usingContentScript();

async function main() {
  const connection = await content.connect({
    target: chromeTarget.background(),
  });
  const documents = connection.get(DocumentToken);
  console.log(await documents.summarize("intro"));
}

void main().catch(console.error);

There are three distinct operations:

  1. connect asynchronously acquires a ready session.
  2. get synchronously checks the service catalog and returns a proxy.
  3. await consumes the method call and receives its remote result.

Run It

Build the extension with your project’s build command, load or reload it in chrome://extensions, and open a page matched by its content-script registration. In that page’s developer console, expect:

Summary of intro

If it does not appear, check that the background and content bundles both run, both import the same shared Token definition, and the extension was reloaded after rebuilding. See Troubleshooting for connection and service-acquisition failures.

Next Steps

Edit this page on GitHub