oRPC
background

Procedures

Understanding procedures - the building blocks of oRPC business logic

Introduction

In oRPC, a procedure consists of two main parts:

  1. Contract: Defines the route, input, and output specifications
  2. Implementation: Contains middleware and business logic handler

The contract part can be separated using the Contract-First approach, allowing for better code organization and team collaboration.

Anatomy of a Procedure

Here's a comprehensive example of an oRPC procedure:

import {  } from 'zod'
import { ,  } from '@orpc/server'
 
// Define context type for full type inference
const  /* public access */ = .<{?: {: string}}>()
 
const  = 
    .({ : 'GET', : '/{id}' }) // Optional: if you want custom api under OpenAPI Specifications
    .(.({ : .() })) // Optional
    .(.({ : .(), : .() })) // Optional
    .(async (, , ) => { // Optional
        // Middleware runs before the handler
        // input, context, and meta are fully typed
        
        // Example: Authentication check
        if (!.) {
            throw new ({
                : 'UNAUTHORIZED',
                : 'Authentication required'
            })
        }
 
        // Modify context for next middleware/handler
        const  = await .({
            : {
                : . // TypeScript will infer user as NonNullable
            }
        })
 
        // do something on success
        const  = .
 
        return 
    })
    
    // Define handler with business logic
    .(async (, , ) => {
        // Implement your business logic here
        
        return {
            : .,
            : 'Sample User'
        }
    })

On this page