Skip to content

Interceptors

Interceptors are the primary mechanism for cross-cutting concerns in Connectum. They wrap RPC calls at the transport level -- adding error handling, timeouts, retries, validation, and more -- without touching business logic.

Quick Start

typescript
import { createServer } from '@connectum/core';
import { createDefaultInterceptors } from '@connectum/interceptors';
import routes from '#gen/routes.js';

const server = createServer({
  services: [routes],
  port: 5000,
  // errorHandler + validation by default; resilience is opt-in
  interceptors: createDefaultInterceptors({
    timeout: { duration: 10_000 },  // explicitly enabled
    retry: { maxRetries: 5 },       // explicitly enabled
  }),
  shutdown: { autoShutdown: true },
});

await server.start();

Key Concepts

How Interceptors Work

A ConnectRPC interceptor is a function that receives next and returns a handler. The handler gets control before and after each request, forming a layered pipeline:

Request  -> interceptor1 -> interceptor2 -> ... -> handler
Response <- interceptor1 <- interceptor2 <- ... <- handler

Built-in Chain

createDefaultInterceptors() is a chain factory for 8 production-ready interceptors in a fixed order:

#InterceptorPurposeDefault
1errorHandlerNormalizes errors into ConnectErrorEnabled
2timeoutLimits request execution timeOpt-in (30s when enabled)
3bulkheadLimits concurrent requestsOpt-in (capacity 10, queue 10 when enabled)
4circuitBreakerPrevents cascading failures (outbound pattern)Opt-in (threshold 5 when enabled)
5retryRetries transient failures with exponential backoffOpt-in (3 retries when enabled)
6fallbackGraceful degradationOpt-in (requires a handler)
7validationValidates via @connectrpc/validateEnabled
8serializerJSON serialization for protobufOpt-in

No hidden behavioral logic. Only structural interceptors (errorHandler, validation) are enabled by default. Resilience interceptors (timeout, bulkhead, circuitBreaker, retry) alter request behavior and must be enabled explicitly with true or an options object.

Per-Method Routing

Three approaches for applying interceptors selectively:

ScenarioApproach
Interceptor bound to a specific service routerConnectRPC native (router.service())
Declarative routing by patterncreateMethodFilterInterceptor
Dynamic logic, filtering by request contentCustom interceptor

Learn More