Skip to content

Publish Client to NPM

Publishing your oRPC client to NPM allows users to easily consume your APIs as a software development kit (SDK).

INFO

Before you start, we recommend watching some publish typescript library to npm tutorials to get familiar with the process.

Prerequisites

You must have a project already set up with oRPC. Contract First is the preferred approach. If you haven't set one up yet, you can clone an oRPC playground and start from there.

INFO

In this guide, we'll use pnpm as the package manager and tsdown for bundling the package. You can use other package managers and bundlers, but the commands may differ.

Export & Scripts

First, create a src/index.ts file to set up and export your client.

src/index.ts
ts
import { createORPCClient } from '@orpc/client'
import { RPCLink } from '@orpc/client/fetch'
import type { ContractRouterClient } from '@orpc/contract'

export function createMyApi(apiKey: string): ContractRouterClient<typeof contract> {
  const link = new RPCLink({
    url: 'https://example.com/rpc',
    headers: {
      'x-api-key': apiKey,
    }
  })

  return createORPCClient(link)
}

INFO

This example uses RPCLink combined with Contract First to create a client. This is just an example, you can use any other link or client setup that you prefer.

Next, configure your package.json with the necessary fields for publishing to NPM.

package.json
json
{
  "name": "<package-name>", 
  "type": "module",
  "version": "0.0.0", 
  "publishConfig": {
    "access": "public"
  },
  "exports": {
    ".": {
      "types": "./dist/index.d.ts", 
      "import": "./dist/index.js", 
      "default": "./dist/index.js"
    }
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "tsdown --dts src/index.ts", 
    "release": "pnpm publish"
  },
  "dependencies": {
    "@orpc/client": "...", 
    "@orpc/contract": "..."
    // ... other dependencies that `src/index.ts` depends on
  },
  "devDependencies": {
    "tsdown": "latest",
    "typescript": "latest"
  }
}

Build & Publish

After completing the necessary setup, commit your changes and run the following commands to build and publish your client to NPM:

bash
pnpm login # if you haven't logged in yet
pnpm run build
pnpm run release

Install & Use

Once your client is published to NPM, you can install it in your project and use it like this:

bash
pnpm add "<package-name>"
example.ts
ts
import { createMyApi } from '<package-name>'

const myApi = createMyApi('your-api-key')

const output = await myApi.someMethod('input')

INFO

This client includes all oRPC client features, so you can use it with any supported integrations like Tanstack Query.

Released under the MIT License.