### Install oRPC Server and Client Packages Source: https://orpc.dev/docs/getting-started Installs the latest versions of the oRPC server and client packages using various package managers. Ensure you have Node.js 18+ and a compatible package manager installed. ```sh npm install @orpc/server@latest @orpc/client@latest ``` ```sh yarn add @orpc/server@latest @orpc/client@latest ``` ```sh pnpm add @orpc/server@latest @orpc/client@latest ``` ```sh bun add @orpc/server@latest @orpc/client@latest ``` ```sh deno add npm:@orpc/server@latest npm:@orpc/client@latest ``` -------------------------------- ### Install oRPC OpenAPI dependencies Source: https://orpc.dev/docs/openapi/getting-started Installs the necessary core oRPC and OpenAPI packages required to build compliant APIs. ```npm npm install @orpc/server@latest @orpc/client@latest @orpc/openapi@latest ``` ```yarn yarn add @orpc/server@latest @orpc/client@latest @orpc/openapi@latest ``` ```pnpm pnpm add @orpc/server@latest @orpc/client@latest @orpc/openapi@latest ``` ```bun bun add @orpc/server@latest @orpc/client@latest @orpc/openapi@latest ``` ```deno deno add npm:@orpc/server@latest npm:@orpc/client@latest npm:@orpc/openapi@latest ``` -------------------------------- ### Install and consume the published SDK Source: https://orpc.dev/docs/advanced/publish-client-to-npm Commands and code examples for installing the published package and initializing the client in a consumer application. ```bash pnpm add "" ``` ```typescript import { createMyApi } from '' const myApi = createMyApi('your-api-key') const output = await myApi.someMethod('input') ``` -------------------------------- ### Call oRPC Procedure Source: https://orpc.dev/docs/getting-started Demonstrates calling an oRPC procedure ('planet.find') with type-safe arguments and auto-completion. This example assumes the 'orpc' client instance is imported from './shared/planet'. ```ts import { orpc } from './shared/planet' // ---cut--- const planet = await orpc.planet.find({ id: 1 }) orpc.planet.create // ^| ``` -------------------------------- ### Monorepo Project Structure Examples Source: https://orpc.dev/docs/best-practices/monorepo-setup Illustrates common monorepo structures for oRPC projects, including 'Contract First', 'Service First', and 'Hybrid' approaches. These structures help organize shared contracts, services, and client implementations. ```txt apps/ ├─ api/ // Import `core-contract` and implement it ├─ web/ // Import `core-contract` and set up @orpc/client here ├─ app/ packages/ ├─ core-contract/ // Define contract with @orpc/contract ├─ .../ ``` ```txt apps/ ├─ api/ // Import `core-service` and run it in your environment ├─ web/ // Import `core-service` and set up @orpc/client here ├─ app/ packages/ ├─ core-service/ // Define procedures with @orpc/server ├─ .../ ``` ```txt apps/ ├─ api/ // Import `core-service` and set up @orpc/server here ├─ web/ // Import `core-contract` and set up @orpc/client here ├─ app/ packages/ ├─ core-contract/ // Define contract with @orpc/contract ├─ core-service/ // Import `core-contract` and implement it ├─ .../ ``` -------------------------------- ### Client Setup: oRPC vs tRPC Source: https://orpc.dev/docs/migrations/from-trpc Shows how to set up clients for oRPC and tRPC. oRPC uses `createORPCClient` with `RPCLink`, while tRPC uses `createTRPCProxyClient` with `httpLink`. Both examples demonstrate basic usage for fetching data. ```typescript import { createORPCClient, onError } from '@orpc/client' import { RPCLink } from '@orpc/client/fetch' import { RouterClient } from '@orpc/server' const link = new RPCLink({ url: 'http://localhost:3000/api/orpc', interceptors: [ onError((error) => { console.error(error) }) ], }) export const client: RouterClient = createORPCClient(link) // ---------------- Usage ---------------- const { planets } = await client.planet.list({ cursor: 0 }) ``` ```typescript import { createTRPCProxyClient, httpLink } from '@trpc/client' export const client = createTRPCProxyClient({ links: [ httpLink({ url: 'http://localhost:3000/api/trpc' }) ] }) // ---------------- Usage ---------------- const { planets } = await client.planet.list.query({ cursor: 0 }) ``` -------------------------------- ### Access API endpoints via cURL Source: https://orpc.dev/docs/openapi/getting-started Example commands to interact with the running oRPC server using standard HTTP methods. ```bash curl -X GET http://127.0.0.1:3000/planets curl -X GET http://127.0.0.1:3000/planets/1 curl -X POST http://127.0.0.1:3000/planets \ -H 'Authorization: Bearer token' \ -H 'Content-Type: application/json' \ -d '{"name": "name"}' ``` -------------------------------- ### Server Setup: oRPC vs tRPC (Next.js) Source: https://orpc.dev/docs/migrations/from-trpc Provides examples for setting up the server for oRPC and tRPC using Next.js. oRPC uses `RPCHandler` from `@orpc/server/fetch`, while tRPC uses `fetchRequestHandler` from `@trpc/server/adapters/fetch`. ```typescript import { RPCHandler } from '@orpc/server/fetch' const handler = new RPCHandler(appRouter, { interceptors: [ async ({ next }) => { try { return await next() } catch (error) { console.error(error) throw error } } ] }) async function handleRequest(request: Request) { const { response } = await handler.handle(request, { prefix: '/api/orpc', context: await createORPCContext(request) }) return response ?? new Response('Not found', { status: 404 }) } export const GET = handleRequest export const POST = handleRequest ``` ```typescript import { fetchRequestHandler } from '@trpc/server/adapters/fetch' function handler(req: Request) { return fetchRequestHandler({ endpoint: '/api/trpc', req, router: appRouter, createContext: () => createTRPCContext(req), onError: ({ path, error }) => { console.error( `❌ tRPC failed on ${path ?? ''}: ${error.message}` ) } }) } export { handler as GET, handler as POST } ``` -------------------------------- ### Create oRPC Server with Node.js HTTP Source: https://orpc.dev/docs/getting-started Sets up an HTTP server using Node.js to handle oRPC requests. It utilizes RPCHandler with CORSPlugin and an onError interceptor. This example assumes the router is defined in './shared/planet'. ```ts import { router } from './shared/planet' // ---cut--- import { createServer } from 'node:http' import { RPCHandler } from '@orpc/server/node' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { plugins: [new CORSPlugin()], interceptors: [ onError((error) => { console.error(error) }), ], }) const server = createServer(async (req, res) => { const result = await handler.handle(req, res, { context: { headers: req.headers } }) if (!result.matched) { res.statusCode = 404 res.end('No procedure matched') } }) server.listen( 3000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:3000') ) ``` -------------------------------- ### Install oRPC Server Source: https://orpc.dev/docs/contract-first/implement-contract Commands to install the @orpc/server package using various JavaScript package managers. ```npm npm install @orpc/server@latest ``` ```yarn yarn add @orpc/server@latest ``` ```pnpm pnpm add @orpc/server@latest ``` ```bun bun add @orpc/server@latest ``` ```deno deno add npm:@orpc/server@latest ``` -------------------------------- ### Define OpenAPI-compatible routes Source: https://orpc.dev/docs/openapi/getting-started Demonstrates how to define RESTful routes using oRPC's 'os' builder, incorporating Zod schemas for input validation and output serialization. ```typescript import type { IncomingHttpHeaders } from 'node:http' import { ORPCError, os } from '@orpc/server' import * as z from 'zod' const PlanetSchema = z.object({ id: z.number().int().min(1), name: z.string(), description: z.string().optional(), }) export const listPlanet = os .route({ method: 'GET', path: '/planets' }) .input(z.object({ limit: z.number().int().min(1).max(100).optional(), cursor: z.number().int().min(0).default(0), })) .output(z.array(PlanetSchema)) .handler(async ({ input }) => { return [{ id: 1, name: 'name' }] }) export const findPlanet = os .route({ method: 'GET', path: '/planets/{id}' }) .input(z.object({ id: z.coerce.number().int().min(1) })) .output(PlanetSchema) .handler(async ({ input }) => { return { id: 1, name: 'name' } }) export const createPlanet = os .$context<{ headers: IncomingHttpHeaders }>() .use(({ context, next }) => { const user = parseJWT(context.headers.authorization?.split(' ')[1]) if (user) { return next({ context: { user } }) } throw new ORPCError('UNAUTHORIZED') }) .route({ method: 'POST', path: '/planets' }) .input(PlanetSchema.omit({ id: true })) .output(PlanetSchema) .handler(async ({ input, context }) => { return { id: 1, name: 'name' } }) export const router = { planet: { list: listPlanet, find: findPlanet, create: createPlanet } } ``` -------------------------------- ### Install oRPC Contract Package Source: https://orpc.dev/docs/contract-first/define-contract Installs the `@orpc/contract` package using various package managers like npm, yarn, pnpm, bun, and deno. This is the first step to start using oRPC for contract-first development. ```sh npm install @orpc/contract@latest ``` ```sh yarn add @orpc/contract@latest ``` ```sh pnpm add @orpc/contract@latest ``` ```sh bun add @orpc/contract@latest ``` ```sh deno add npm:@orpc/contract@latest ``` -------------------------------- ### Optimize SSR with Server-Side oRPC Client in Solid Start Source: https://orpc.dev/docs/adapters/solid-start Implements a server-side oRPC client for Solid Start to optimize SSR by reducing HTTP requests. It conditionally imports a server-specific client and provides a fallback to a client-side instance if the server-side client is unavailable. ```typescript if (typeof window === 'undefined') { await import('./orpc.server') } import type { RouterClient } from '@orpc/server' import { RPCLink } from '@orpc/client/fetch' import { createORPCClient } from '@orpc/client' declare global { var $client: RouterClient | undefined } const link = new RPCLink({ url: () => { if (typeof window === 'undefined') { throw new Error('RPCLink is not allowed on the server side.') } return `${window.location.origin}/rpc` }, }) /** * Fallback to client-side client if server-side client is not available. */ export const client: RouterClient = globalThis.$client ?? createORPCClient(link) ``` ```typescript import { createRouterClient } from '@orpc/server' import { getRequestEvent } from 'solid-js/web' if (typeof window !== 'undefined') { throw new Error('This file should not be imported in the browser') } globalThis.$client = createRouterClient(router, { /** * Provide initial context if needed. * * Because this client instance is shared across all requests, * only include context that's safe to reuse globally. * For per-request context, use middleware context or pass a function as the initial context. */ context: async () => { const headers = getRequestEvent()?.request.headers return { headers, // provide headers if initial context required } }, }) ``` -------------------------------- ### Create oRPC Client Source: https://orpc.dev/docs/getting-started Initializes an oRPC client using RPCLink for fetch requests. It connects to the specified server URL and includes authorization headers. The client is strongly typed based on the provided router definition. ```ts import { router } from './shared/planet' // ---cut--- import type { RouterClient } from '@orpc/server' import { createORPCClient } from '@orpc/client' import { RPCLink } from '@orpc/client/fetch' const link = new RPCLink({ url: 'http://127.0.0.1:3000', headers: { Authorization: 'Bearer token' }, }) export const orpc: RouterClient = createORPCClient(link) ``` -------------------------------- ### Install Publisher Package Source: https://orpc.dev/docs/helpers/publisher Installs the experimental publisher package for oRPC using various package managers like npm, yarn, pnpm, bun, and deno. ```sh npm install @orpc/experimental-publisher@latest ``` ```sh yarn add @orpc/experimental-publisher@latest ``` ```sh pnpm add @orpc/experimental-publisher@latest ``` ```sh bun add @orpc/experimental-publisher@latest ``` ```sh deno add npm:@orpc/experimental-publisher@latest ``` -------------------------------- ### Configure oRPC Server Handler in Solid Start Source: https://orpc.dev/docs/adapters/solid-start Sets up the oRPC request handler for Solid Start server routes. It utilizes RPCHandler to process incoming requests and returns the response or a 404 if not found. This handler is exported for all HTTP methods. ```typescript import type { APIEvent } from '@solidjs/start/server' import { RPCHandler } from '@orpc/server/fetch' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { interceptors: [ onError((error) => { console.error(error) }), ], }) async function handle({ request }: APIEvent) { const { response } = await handler.handle(request, { prefix: '/rpc', context: {} // Provide initial context if needed }) return response ?? new Response('Not Found', { status: 404 }) } export const HEAD = handle export const GET = handle export const POST = handle export const PUT = handle export const PATCH = handle export const DELETE = handle ``` ```typescript import { POST as handle } from './[...rest]' export const HEAD = handle export const GET = handle export const POST = handle export const PUT = handle export const PATCH = handle export const DELETE = handle ``` -------------------------------- ### Configure oRPC Client Link in Solid Start Source: https://orpc.dev/docs/adapters/solid-start Sets up the oRPC client link for use in Solid Start applications. It dynamically determines the URL based on the environment (server or browser) and uses `getRequestEvent` to provide request headers for SSR compatibility. ```typescript import { RPCLink } from '@orpc/client/fetch' import { getRequestEvent } from 'solid-js/web' const link = new RPCLink({ url: `${typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000'}/rpc`, headers: () => getRequestEvent()?.request.headers ?? {}, }) ``` -------------------------------- ### Create an OpenAPI server Source: https://orpc.dev/docs/openapi/getting-started Configures a Node.js HTTP server using the OpenAPIHandler to process requests against the defined router. ```typescript import { createServer } from 'node:http' import { OpenAPIHandler } from '@orpc/openapi/node' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new OpenAPIHandler(router, { plugins: [new CORSPlugin()], interceptors: [ onError((error) => { console.error(error) }), ], }) const server = createServer(async (req, res) => { const result = await handler.handle(req, res, { context: { headers: req.headers } }) if (!result.matched) { res.statusCode = 404 res.end('No procedure matched') } }) server.listen(3000, '127.0.0.1', () => console.log('Listening on 127.0.0.1:3000')) ``` -------------------------------- ### Install OpenAPILink Client Source: https://orpc.dev/docs/openapi/client/openapi-link Installs the latest version of the OpenAPILink client package using various package managers. ```sh npm install @orpc/openapi-client@latest ``` ```sh yarn add @orpc/openapi-client@latest ``` ```sh pnpm add @orpc/openapi-client@latest ``` ```sh bun add @orpc/openapi-client@latest ``` ```sh deno add npm:@orpc/openapi-client@latest ``` -------------------------------- ### Setting up Strict GET Method Plugin with RPCHandler (TypeScript) Source: https://orpc.dev/docs/plugins/strict-get-method This code illustrates how to integrate the `StrictGetMethodPlugin` into an `RPCHandler` instance. It shows the import statement for the plugin and its instantiation within the `plugins` array during `RPCHandler` setup. ```typescript import { RPCHandler } from '@orpc/server/fetch' import { router } from './shared/planet' // ---cut--- import { StrictGetMethodPlugin } from '@orpc/server/plugins' const handler = new RPCHandler(router, { plugins: [ new StrictGetMethodPlugin() ], }) ``` -------------------------------- ### Format Logs with pino-pretty Source: https://orpc.dev/docs/integrations/pino Example command to pipe development logs through pino-pretty for improved readability. ```bash npm run dev | npx pino-pretty ``` -------------------------------- ### Setup oRPC Server in Next.js Source: https://orpc.dev/docs/adapters/next Configures oRPC handlers for Next.js routing. Includes examples for App Router using Route Handlers and Pages Router using API routes with body parser configuration. ```typescript import { RPCHandler } from '@orpc/server/fetch' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { interceptors: [ onError((error) => { console.error(error) }), ], }) async function handleRequest(request: Request) { const { response } = await handler.handle(request, { prefix: '/rpc', context: {}, // Provide initial context if needed }) return response ?? new Response('Not found', { status: 404 }) } export const HEAD = handleRequest export const GET = handleRequest export const POST = handleRequest export const PUT = handleRequest export const PATCH = handleRequest export const DELETE = handleRequest ``` ```typescript import { RPCHandler } from '@orpc/server/node' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { interceptors: [ onError((error) => { console.error(error) }), ], }) export const config = { api: { bodyParser: false, }, } export default async (req, res) => { const { matched } = await handler.handle(req, res, { prefix: '/api/rpc', context: {}, // Provide initial context if needed }) if (matched) { return } res.statusCode = 404 res.end('Not found') } ``` -------------------------------- ### Install oRPC Client Package Source: https://orpc.dev/docs/client/client-side Installs the oRPC client package using various package managers like npm, yarn, pnpm, bun, and deno. Ensure you have the appropriate package manager installed for your environment. ```sh npm install @orpc/client@latest ``` ```sh yarn add @orpc/client@latest ``` ```sh pnpm add @orpc/client@latest ``` ```sh bun add @orpc/client@latest ``` ```sh deno add npm:@orpc/client@latest ``` -------------------------------- ### Fetch API Adapters (Bun, Cloudflare, Deno) for ORPC Source: https://orpc.dev/docs/adapters/http This set of examples shows how to use the ORPC `fetch` adapter across different JavaScript runtimes: Bun, Cloudflare Workers, and Deno. All examples configure CORS and error handling, and the handler processes requests with a '/rpc' prefix. ```typescript import { RPCHandler } from '@orpc/server/fetch' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { plugins: [ new CORSPlugin() ], interceptors: [ onError((error) => { console.error(error) }), ], }) Bun.serve({ async fetch(request: Request) { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: {} // Provide initial context if needed }) if (matched) { return response } return new Response('Not found', { status: 404 }) } }) ``` ```typescript import { RPCHandler } from '@orpc/server/fetch' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { plugins: [ new CORSPlugin() ], interceptors: [ onError((error) => { console.error(error) }), ], }) export default { async fetch(request: Request, env: any, ctx: ExecutionContext): Promise { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: {} // Provide initial context if needed }) if (matched) { return response } return new Response('Not found', { status: 404 }) } } ``` ```typescript import { RPCHandler } from '@orpc/server/fetch' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { plugins: [ new CORSPlugin() ], interceptors: [ onError((error) => { console.error(error) }), ], }) Deno.serve(async (request) => { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: {} // Provide initial context if needed }) if (matched) { return response } return new Response('Not found', { status: 404 }) }) ``` -------------------------------- ### Install oRPC Rate Limiter Package Source: https://orpc.dev/docs/helpers/ratelimit Installs the experimental rate limiter package for oRPC using various package managers like npm, yarn, pnpm, bun, and deno. ```sh npm install @orpc/experimental-ratelimit@latest ``` ```sh yarn add @orpc/experimental-ratelimit@latest ``` ```sh pnpm add @orpc/experimental-ratelimit@latest ``` ```sh bun add @orpc/experimental-ratelimit@latest ``` ```sh deno add npm:@orpc/experimental-ratelimit@latest ``` -------------------------------- ### OpenAPIHandler Setup and Integration Source: https://orpc.dev/docs/openapi/openapi-handler Demonstrates how to set up and integrate the OpenAPIHandler with your oRPC application, including plugin and interceptor configuration. ```APIDOC ## OpenAPIHandler Setup and Integration ### Description This section provides a code example for setting up and integrating the `OpenAPIHandler` within an oRPC application. It showcases how to import the handler, configure plugins like `CORSPlugin`, and set up error interceptors. ### Method N/A (This is a setup guide, not a specific endpoint) ### Endpoint N/A (This is a setup guide, not a specific endpoint) ### Parameters N/A ### Request Example N/A ### Response N/A ```ts import { OpenAPIHandler } from '@orpc/openapi/fetch' // or '@orpc/server/node' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new OpenAPIHandler(router, { plugins: [new CORSPlugin()], interceptors: [ onError((error) => { console.error(error) }), ], }) export default async function fetch(request: Request) { const { matched, response } = await handler.handle(request, { prefix: '/api', context: {} // Add initial context if needed }) if (matched) { return response } return new Response('Not Found', { status: 404 }) } ``` ``` -------------------------------- ### Install oRPC OpenAPI package Source: https://orpc.dev/docs/openapi/openapi-handler Commands to install the @orpc/openapi package using various JavaScript package managers. ```npm npm install @orpc/openapi@latest ``` ```yarn yarn add @orpc/openapi@latest ``` ```pnpm pnpm add @orpc/openapi@latest ``` ```bun bun add @orpc/openapi@latest ``` ```deno deno add npm:@orpc/openapi@latest ``` -------------------------------- ### Install Pino Integration Dependencies Source: https://orpc.dev/docs/integrations/pino Commands to install the required oRPC Pino experimental package and the Pino logger using various package managers. ```npm npm install @orpc/experimental-pino@latest pino@latest ``` ```yarn yarn add @orpc/experimental-pino@latest pino@latest ``` ```pnpm pnpm add @orpc/experimental-pino@latest pino@latest ``` ```bun bun add @orpc/experimental-pino@latest pino@latest ``` ```deno deno add npm:@orpc/experimental-pino@latest npm:pino@latest ``` -------------------------------- ### Install oRPC OpenTelemetry Package Source: https://orpc.dev/docs/integrations/opentelemetry Install the `@orpc/otel` package using your preferred package manager (npm, yarn, pnpm, bun, or deno). This package provides the necessary instrumentation for oRPC. ```sh npm install @orpc/otel@latest ``` ```sh yarn add @orpc/otel@latest ``` ```sh pnpm add @orpc/otel@latest ``` ```sh bun add @orpc/otel@latest ``` ```sh deno add npm:@orpc/otel@latest ``` -------------------------------- ### Setup oRPC SWR Utilities Source: https://orpc.dev/docs/integrations/react-swr Initialize the SWR utilities for oRPC by calling `createSWRUtils` with your oRPC client instance. This setup allows you to use the generated SWR hooks for data fetching. You can optionally provide a `path` to avoid key conflicts. ```ts import { router } from './shared/planet' import { RouterClient } from '@orpc/server' import { createSWRUtils } from '@orpc/experimental-react-swr' declare const client: RouterClient export const orpc = createSWRUtils(client) orpc.planet.find.key({ input: { id: 123 } }) // Example with path to avoid key conflicts: // const userORPC = createSWRUtils(userClient, { // path: ['user'] // }) // const postORPC = createSWRUtils(postClient, { // path: ['post'] // }) ``` -------------------------------- ### Install oRPC Solid Query Packages Source: https://orpc.dev/docs/integrations/tanstack-query-old/solid Installs the necessary oRPC and Tanstack Query packages for Solid.js using various package managers like npm, yarn, pnpm, bun, and deno. ```sh npm install @orpc/solid-query@latest @tanstack/solid-query@latest ``` ```sh yarn add @orpc/solid-query@latest @tanstack/solid-query@latest ``` ```sh pnpm add @orpc/solid-query@latest @tanstack/solid-query@latest ``` ```sh bun add @orpc/solid-query@latest @tanstack/solid-query@latest ``` ```sh deno add npm:@orpc/solid-query@latest npm:@tanstack/solid-query@latest ``` -------------------------------- ### Install @orpc/hey-api Package Source: https://orpc.dev/docs/integrations/hey-api Install the @orpc/hey-api package using various package managers like npm, yarn, pnpm, bun, or deno. This package is necessary for converting Hey API clients to oRPC clients. ```sh npm install @orpc/hey-api@latest ``` ```sh yarn add @orpc/hey-api@latest ``` ```sh pnpm add @orpc/hey-api@latest ``` ```sh bun add @orpc/hey-api@latest ``` ```sh deno add npm:@orpc/hey-api@latest ``` -------------------------------- ### Setup OpenAPILink Client Source: https://orpc.dev/docs/openapi/client/openapi-link Demonstrates setting up an OpenAPILink client with a contract, base URL, custom headers, fetch options, and error interceptors. It also shows how to create the oRPC client with type safety using JsonifiedClient. ```ts import type { JsonifiedClient } from '@orpc/openapi-client' import type { ContractRouterClient } from '@orpc/contract' import { createORPCClient, onError } from '@orpc/client' import { OpenAPILink } from '@orpc/openapi-client/fetch' // Assuming 'contract' is imported from './shared/planet' // import { contract } from './shared/planet' const link = new OpenAPILink(contract, { url: 'http://localhost:3000/api', headers: () => ({ 'x-api-key': 'my-api-key', }), fetch: (request, init) => { return globalThis.fetch(request, { ...init, credentials: 'include', // Include cookies for cross-origin requests }) }, interceptors: [ onError((error) => { console.error(error) }) ], }) const client: JsonifiedClient> = createORPCClient(link) ``` -------------------------------- ### Setup and Integration of RPCHandler Source: https://orpc.dev/docs/rpc-handler Demonstrates how to set up and integrate the RPCHandler for handling incoming requests. It includes importing necessary modules, initializing the handler with a router and plugins, and defining a fetch function to process requests. Dependencies include '@orpc/server/fetch' (or '@orpc/server/node'), '@orpc/server/plugins', and '@orpc/server'. ```typescript import { RPCHandler } from '@orpc/server/fetch' // or '@orpc/server/node' import { CORSPlugin } from '@orpc/server/plugins' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { plugins: [ new CORSPlugin() ], interceptors: [ onError((error) => { console.error(error) }) ], }) export default async function fetch(request: Request) { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: {} // Provide initial context if required }) if (matched) { return response } return new Response('Not Found', { status: 404 }) } ``` -------------------------------- ### Setup oRPC Client for Solid Query Source: https://orpc.dev/docs/integrations/tanstack-query-old/solid Demonstrates setting up the oRPC client with Solid Query utilities. It requires a pre-configured server-side or client-side oRPC client and creates query options for data fetching. ```ts import { router } from './shared/planet' import { RouterClient } from '@orpc/server' declare const client: RouterClient // --- import { createORPCSolidQueryUtils } from '@orpc/solid-query' export const orpc = createORPCSolidQueryUtils(client) orpc.planet.find.queryOptions({ input: { id: 123 } }) // ^| ``` -------------------------------- ### Initialize and Use oRPC Client Source: https://orpc.dev/learn-and-contribute/mini-orpc/client-side-client Demonstrates how to instantiate an RPCLink and the resulting oRPC client to invoke remote procedures. This setup enables a server-side-like developer experience on the client. ```typescript const link = new RPCLink({ url: `${window.location.origin}/rpc`, }) export const orpc: RouterClient = createORPCClient(link) const result = await orpc.someProcedure({ input: 'example' }) ``` -------------------------------- ### Initialize RPCLink with HTTP Adapter Source: https://orpc.dev/docs/client/rpc-link Demonstrates how to instantiate an RPCLink with custom headers, fetch configuration, and error interceptors for standard RPC communication. ```typescript import { onError } from '@orpc/client' import { RPCLink } from '@orpc/client/fetch' const link = new RPCLink({ url: 'http://localhost:3000/rpc', headers: () => ({ 'x-api-key': 'my-api-key' }), fetch: (request, init) => { return globalThis.fetch(request, { ...init, credentials: 'include', }) }, interceptors: [ onError((error) => { console.error(error) }) ], }) export const client: RouterClient = createORPCClient(link) ``` -------------------------------- ### Generate OpenAPI Specification using oRPC Source: https://orpc.dev/docs/openapi/getting-started This script initializes an OpenAPIGenerator with Zod schema support to produce an OpenAPI document. It takes an existing oRPC router and metadata as input, outputting a JSON-compatible specification object. ```typescript import { OpenAPIGenerator } from '@orpc/openapi' import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4' import { router } from './shared/planet' const generator = new OpenAPIGenerator({ schemaConverters: [ new ZodToJsonSchemaConverter() ] }) const spec = await generator.generate(router, { info: { title: 'Planet API', version: '1.0.0' } }) console.log(JSON.stringify(spec, null, 2)) ``` -------------------------------- ### Initialize IORedis Publisher Source: https://orpc.dev/docs/helpers/publisher Configures a publisher using IORedis for event broadcasting. This implementation requires two Redis instances for commands and subscriptions, and supports resume functionality. ```typescript import { Redis } from 'ioredis' import { IORedisPublisher } from '@orpc/experimental-publisher/ioredis' const publisher = new IORedisPublisher<{ 'something-updated': { id: string } }>({ commander: new Redis(), // For executing short-lived commands subscriber: new Redis(), // For subscribing to events resumeRetentionSeconds: 60 * 2, // Retain events for 2 minutes to support resume prefix: 'orpc:publisher:', // avoid conflict with other keys customJsonSerializers: [] // optional custom serializers }) ``` -------------------------------- ### Define oRPC App Router with Zod Schemas Source: https://orpc.dev/docs/getting-started Defines an oRPC application router using Zod for input validation. It includes procedures for listing, finding, and creating planets, with context-aware authorization for the create procedure. Requires Zod and @orpc/server. ```ts import type { IncomingHttpHeaders } from 'node:http' import { ORPCError, os } from '@orpc/server' import * as z from 'zod' const PlanetSchema = z.object({ id: z.number().int().min(1), name: z.string(), description: z.string().optional(), }) export const listPlanet = os .input( z.object({ limit: z.number().int().min(1).max(100).optional(), cursor: z.number().int().min(0).default(0), }), ) .handler(async ({ input }) => { // your list code here return [{ id: 1, name: 'name' }] }) export const findPlanet = os .input(PlanetSchema.pick({ id: true })) .handler(async ({ input }) => { // your find code here return { id: 1, name: 'name' } }) export const createPlanet = os .$context<{ headers: IncomingHttpHeaders }>() .use(({ context, next }) => { const user = parseJWT(context.headers.authorization?.split(' ')[1]) if (user) { return next({ context: { user } }) } throw new ORPCError('UNAUTHORIZED') }) .input(PlanetSchema.omit({ id: true })) .handler(async ({ input, context }) => { // your create code here return { id: 1, name: 'name' } }) export const router = { planet: { list: listPlanet, find: findPlanet, create: createPlanet } } // ---cut-after--- declare function parseJWT(token: string | undefined): { userId: number } | null ``` -------------------------------- ### Marking a Procedure for GET Requests (TypeScript) Source: https://orpc.dev/docs/plugins/strict-get-method This snippet demonstrates how to explicitly mark a procedure to accept GET requests using the `method: 'GET'` option within the `os.route` configuration. This is the core mechanism for enabling GET requests for specific RPC procedures. ```typescript import { os } from '@orpc/server' const ping = os .route({ method: 'GET' }) // [!code highlight] .handler(() => 'pong') ``` -------------------------------- ### Initialize oRPC Route Configuration Source: https://orpc.dev/docs/openapi/input-output-structure Example of setting default input/output structure settings for routes using the .$route method. ```typescript const base = os.$route({ inputStructure: 'detailed' }); ``` -------------------------------- ### Configure oRPC Server Route in TanStack Start Source: https://orpc.dev/docs/adapters/tanstack-start Sets up an oRPC handler within a TanStack Start server route. It uses the RPCHandler to process incoming requests and provides a mechanism for error handling. ```typescript import { RPCHandler } from '@orpc/server/fetch' import { createFileRoute } from '@tanstack/react-router' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { interceptors: [ onError((error) => { console.error(error) }), ], }) export const Route = createFileRoute('/api/rpc/$')({ server: { handlers: { ANY: async ({ request }) => { const { response } = await handler.handle(request, { prefix: '/api/rpc', context: {}, // Provide initial context if needed }) return response ?? new Response('Not Found', { status: 404 }) }, }, }, }) ``` -------------------------------- ### Initialize base procedures and middleware Source: https://orpc.dev/docs/migrations/from-trpc Comparison of base procedure initialization and middleware creation between oRPC and tRPC. Demonstrates setting up context, timing middleware, and protected procedures. ```typescript (oRPC) import { ORPCError, os } from '@orpc/server' export async function createRPCContext(opts: { headers: Headers }) { const session = await auth() return { headers: opts.headers, session, } } const o = os.$context>>() const timingMiddleware = o.middleware(async ({ next, path }) => { const start = Date.now() try { return await next() } finally { console.log(`[oRPC] ${path} took ${Date.now() - start}ms to execute`) } }) export const publicProcedure = o.use(timingMiddleware) export const protectedProcedure = publicProcedure.use(({ context, next }) => { if (!context.session?.user) { throw new ORPCError('UNAUTHORIZED') } return next({ context: { session: { ...context.session, user: context.session.user } } }) }) ``` ```typescript (tRPC) import { initTRPC, TRPCError } from '@trpc/server' import superjson from 'superjson' export async function createRPCContext(opts: { headers: Headers }) { const session = await auth() return { headers: opts.headers, session, } } const t = initTRPC.context().create({ transformer: superjson, }) export const createTRPCRouter = t.router const timingMiddleware = t.middleware(async ({ next, path }) => { const start = Date.now() const result = await next() const end = Date.now() console.log(`[tRPC] ${path} took ${end - start}ms to execute`) return result }) export const publicProcedure = t.procedure.use(timingMiddleware) export const protectedProcedure = t.procedure .use(timingMiddleware) .use(({ ctx, next }) => { if (!ctx.session?.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }) } return next({ ctx: { session: { ...ctx.session, user: ctx.session.user }, }, }) }) ``` -------------------------------- ### Install @orpc/nest package Source: https://orpc.dev/docs/openapi/integrations/implement-contract-in-nest Commands to install the @orpc/nest library using various package managers. ```npm npm install @orpc/nest@latest ``` ```yarn yarn add @orpc/nest@latest ``` ```pnpm pnpm add @orpc/nest@latest ``` ```bun bun add @orpc/nest@latest ``` ```deno deno add npm:@orpc/nest@latest ``` -------------------------------- ### Setup OpenAPI Reference Plugin with TypeScript Source: https://orpc.dev/docs/openapi/plugins/openapi-reference This snippet demonstrates how to set up the OpenAPI Reference Plugin in a TypeScript project. It shows the necessary imports from '@orpc/zod/zod4' and '@orpc/openapi/plugins'. The plugin is configured with options such as the documentation provider ('swagger' or 'scalar'), schema converters (e.g., ZodToJsonSchemaConverter), and OpenAPI specification generation options including API info and server details. The default paths for documentation and the specification can be customized. ```typescript import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4' import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins' const handler = new OpenAPIHandler(router, { plugins: [ new OpenAPIReferencePlugin({ docsProvider: 'swagger', // default: 'scalar' schemaConverters: [ new ZodToJsonSchemaConverter(), ], specGenerateOptions: { info: { title: 'ORPC Playground', version: '1.0.0', }, servers: [ // or let the plugin auto-infer from the request { url: 'https://api.example.com/v1', }, ], }, }), ] }) ``` -------------------------------- ### Install oRPC tRPC integration Source: https://orpc.dev/docs/openapi/integrations/trpc Commands to install the @orpc/trpc package using various JavaScript package managers. ```npm npm install @orpc/trpc@latest ``` ```yarn yarn add @orpc/trpc@latest ``` ```pnpm pnpm add @orpc/trpc@latest ``` ```bun bun add @orpc/trpc@latest ``` ```deno deno add npm:@orpc/trpc@latest ``` -------------------------------- ### Initialize oRPC Server in Electron Main Process Source: https://orpc.dev/docs/adapters/electron Sets up an RPCHandler to listen for incoming message ports from the renderer process via IPC. It upgrades the received port to handle RPC requests and includes an error interceptor. ```typescript import { RPCHandler } from '@orpc/server/message-port' import { onError } from '@orpc/server' const handler = new RPCHandler(router, { interceptors: [ onError((error) => { console.error(error) }), ], }) app.whenReady().then(() => { ipcMain.on('start-orpc-server', async (event) => { const [serverPort] = event.ports handler.upgrade(serverPort) serverPort.start() }) }) ``` -------------------------------- ### Install oRPC dependencies Source: https://orpc.dev/docs/migrations/from-trpc Commands to remove tRPC packages and install their oRPC equivalents across various package managers. ```npm npm uninstall @trpc/server @trpc/client @trpc/tanstack-react-query npm install @orpc/server@latest @orpc/client@latest @orpc/tanstack-query@latest ``` ```yarn yarn remove @trpc/server @trpc/client @trpc/tanstack-react-query yarn add @orpc/server@latest @orpc/client@latest @orpc/tanstack-query@latest ``` ```pnpm pnpm remove @trpc/server @trpc/client @trpc/tanstack-react-query pnpm add @orpc/server@latest @orpc/client@latest @orpc/tanstack-query@latest ``` ```bun bun remove @trpc/server @trpc/client @trpc/tanstack-react-query bun add @orpc/server@latest @orpc/client@latest @orpc/tanstack-query@latest ``` ```deno deno remove npm:@trpc/server npm:@trpc/client npm:@trpc/tanstack-react-query deno add npm:@orpc/server@latest npm:@orpc/client@latest npm:@orpc/tanstack-query@latest ```