How RPC Works
This project uses ORPC for type-safe remote procedure calls between the client and server. ORPC provides end-to-end type safety, ensuring that your API calls are validated at compile time.Architecture
Endpoint Structure
All RPC endpoints are served through a single Next.js route:App Router
The main router is defined insrc/routers/index.ts:
AppRouter), which is used by the client for type inference.
RPC Handler Setup
The RPC handler is configured insrc/app/rpc/[...all]/route.ts:
- prefix:
/rpc- All RPC calls are prefixed with this path - context: Created per-request, includes session data from Better Auth
Context Creation
Each request gets a context with the current user’s session:Request/Response Format
ORPC uses a JSON-RPC-like protocol over HTTP. The client automatically handles serialization and deserialization.Client Setup
The client is configured insrc/utils/orpc.ts:
Example Request
Error Handling
ORPC uses typed errors throughORPCError:
UNAUTHORIZED- User is not authenticatedFORBIDDEN- User lacks permissionsBAD_REQUEST- Invalid inputNOT_FOUND- Resource not foundINTERNAL_SERVER_ERROR- Server error
Client-Side Error Handling
Errors are automatically caught and can be handled in React Query:Type Safety
One of ORPC’s key features is end-to-end type safety:- Input Validation: Zod schemas validate input on the server
- Type Inference: Client automatically infers types from the router
- Autocompletion: Full IDE support for all procedures and their inputs/outputs
- Compile-Time Checks: TypeScript catches mismatches before runtime
Example
Procedures Types
Public Procedures
Available to all users, authenticated or not:Protected Procedures
Require authentication via therequireAuth middleware: