Overview
The Contract Kit server runtime provides a framework-agnostic way to handle HTTP requests with full type safety, validation, and middleware support.Server Architecture
The server runtime consists of:- Adapters: Framework-specific implementations (Next.js, Express, etc.)
- Request Pipeline: Parsing, validation, middleware execution
- Context: Request-scoped data and dependencies
- Error Handling: Automatic error mapping and responses
Creating a Server
Basic Setup
Implementing Routes
Handle Function
Thehandle function is where you implement your business logic:
Accessing Request Data
All request data is automatically parsed and validated:Middleware
Global Middleware
Add middleware that runs on every request:Metadata-Aware Middleware
Use contract metadata to opt into middleware behavior:Context
Creating Context
Context is created per-request and provides access to dependencies:Using Context
Access context in your route handlers:Error Handling
Automatic Validation Errors
Contract Kit automatically validates requests and returns appropriate errors:Custom Error Handling
Handle specific errors in your route:Global Error Handler
Define a catch-all error handler:Response Types
Success Responses
Return successful responses with the correct status and body:Error Responses
Return error responses that match your contract:Next.js Integration
App Router
Pages Router
Best Practices
Keep handlers thin
Keep handlers thin
Move business logic to use cases or services. Handlers should orchestrate, not implement.
Use dependency injection
Use dependency injection
Always access external dependencies through ports to keep your code testable.
Validate at the contract level
Validate at the contract level
Define comprehensive validation in your contracts, not in your handlers.
Handle errors gracefully
Handle errors gracefully
Return appropriate status codes and error messages that match your contract.
Log important events
Log important events
Use structured logging through a provider for debugging and monitoring.