Publish Client to NPM
Publishing your oRPC client to NPM allows users to easily consume your APIs as a software development kit (SDK).
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.
Export & Scripts
First, create a src/index.ts file to set up and export your client.
import { createORPCClient } from '@orpc/client'
import { RPCLink } from '@orpc/client/fetch'
import type { RouterContractClient } from '@orpc/contract'
export function createMyApi(apiKey: string): RouterContractClient<typeof contract> {
const link = new RPCLink({
origin: 'https://example.com',
url: '/rpc',
headers: {
'x-api-key': apiKey,
}
})
return createORPCClient(link)
}
Next, configure your package.json with the necessary fields for publishing to NPM.
{
"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:
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:
pnpm add "<package-name>"
import { createMyApi } from '<package-name>'
const myApi = createMyApi('your-api-key')
const output = await myApi.someMethod('input')