Interceptors
Keep handlers focused on business decisions. Interceptors wrap the RPC with shared behavior such as error handling, validation or a timeout.
Wrap next, then observe the return
Change the order. Check the header.
stockTag adds a response header. Move audit inside it: does its after-step see the header yet?
Selected composition
interceptors: [audit, stockTag]
audit and stockTag are created by the factories below. Their write callback appends to this log.
import type { Interceptor } from '@connectrpc/connect';
export function createAudit(write: (entry: string) => void): Interceptor {
return (next) => async (req) => {
write('audit: before');
const response = await next(req);
const source = response.header.get('x-stock-source');
write(`audit: after (header = ${source ?? 'unset'})`);
return response;
};
}
Observed execution log
audit: beforestockTag: beforehandler: return 7 unitsstockTag: after (set header)audit: after (header = fixture)
- Caller’s x-stock-source
fixture- Handler calls
- 1
{"units":7}
Read the after-steps from the inside out. Compare what audit saw with the header the caller received.
Runs real custom interceptors through Connect-ES’s in-memory router transport. No network request is sent. The inventory is fixture data; this page does not start a Connectum server.
Static successful run. Editing requires JavaScript.
Compare the compositions without JavaScript
audit → stockTag · Return stock · OK
audit: beforestockTag: beforehandler: return 7 unitsstockTag: after (set header)audit: after (header = fixture)
Caller’s x-stock-source: fixture.
stockTag → audit · Return stock · OK
stockTag: beforeaudit: beforehandler: return 7 unitsaudit: after (header = unset)stockTag: after (set header)
Caller’s x-stock-source: fixture.
audit only · Return stock · OK
audit: beforehandler: return 7 unitsaudit: after (header = unset)
Caller’s x-stock-source: (not set).
audit → stockTag · Throw NotFound · NotFound
audit: beforestockTag: beforehandler: throw NotFound
Caller’s x-stock-source: (not set).
stockTag → audit · Throw NotFound · NotFound
stockTag: beforeaudit: beforehandler: throw NotFound
Caller’s x-stock-source: (not set).
audit only · Throw NotFound · NotFound
audit: beforehandler: throw NotFound
Caller’s x-stock-source: (not set).
Run the same interceptors on a real Connectum server
The standalone test sends all six composition/outcome combinations over HTTP and checks their logs, responses and headers.
cd .vitepress/interceptors/example
pnpm install --frozen-lockfile
pnpm generate
pnpm typecheck
pnpm test
The custom interceptors are appended after the default error handling and validation:
import { createServer, defineService } from '@connectum/core';
import { createDefaultInterceptors } from '@connectum/interceptors';
import type { Settings } from '../../settings.ts';
import { InventoryService } from '../gen/shop/v1/inventory_pb.ts';
import { createChain } from './chain.ts';
import { checkStock } from './inventory.ts';
export function createExampleServer(settings: Settings, write: (entry: string) => void, onHandler: () => void) {
return createServer({
services: [
defineService(InventoryService, {
checkStock(req) {
onHandler();
return checkStock(req, write);
},
}),
],
interceptors: [...createDefaultInterceptors({ errorHandler: { logErrors: false } }), ...createChain(settings.chain, write)],
host: '127.0.0.1',
port: 0,
allowHTTP1: true,
shutdown: { autoShutdown: false },
});
}
audit.ts
import type { Interceptor } from '@connectrpc/connect';
export function createAudit(write: (entry: string) => void): Interceptor {
return (next) => async (req) => {
write('audit: before');
const response = await next(req);
const source = response.header.get('x-stock-source');
write(`audit: after (header = ${source ?? 'unset'})`);
return response;
};
}
stockTag.ts
import type { Interceptor } from '@connectrpc/connect';
export function createStockTag(write: (entry: string) => void): Interceptor {
return (next) => async (req) => {
write('stockTag: before');
const response = await next(req);
response.header.set('x-stock-source', 'fixture');
write('stockTag: after (set header)');
return response;
};
}
handler.ts
import { Code, ConnectError } from '@connectrpc/connect';
const stock = new Map([['A-1', 7]]);
export function checkStock(req: { sku: string }, write: (entry: string) => void) {
const units = stock.get(req.sku);
if (units === undefined) {
write('handler: throw NotFound');
throw new ConnectError('SKU not found', Code.NotFound);
}
write(`handler: return ${units} units`);
return { units };
}
How composition and selection fit together
Start with the default chain
import { createServer } from '@connectum/core';
import { createDefaultInterceptors } from '@connectum/interceptors';
const server = createServer({
services: [routes],
interceptors: createDefaultInterceptors(),
});Here routes is your service registration. The default chain includes error handling and validation; resilience features are opt-in.
Opt into timeout and retry
const interceptors = createDefaultInterceptors({
timeout: { duration: 10_000 },
retry: { maxRetries: 2 },
});Pass this chain as the server's interceptors. Retry can repeat work; enable it only where the operation is safe to retry.
Error handling and validation are structural defaults. Timeout, bulkhead, circuit breaker, retry, fallback, and serializer behavior is opt-in because it changes request semantics. Chain order and enablement rules live in Usage and chain composition; each interceptor has its own focused guide. Exact fields live in DefaultInterceptorOptions.
Choose the extension route
Start with the built-in chain, write a custom interceptor, or scope it to selected methods.
Other middleware tasks and exact APIs
| Need | Route |
|---|---|
| Configure the supported chain | Built-in interceptors |
| Add business-specific middleware | Custom interceptors |
| Apply behavior to selected services or methods | Method filtering |
| Authenticate or authorize calls | Auth and authz |
| Trace incoming or outgoing calls | Tracing |
| Look up an exact factory or option | @connectum/interceptors API |
Use native router scoping when an interceptor belongs to one service, a method-filter interceptor for declarative name patterns, and a custom interceptor only when selection depends on runtime request data.
Native per-service interceptors replace, rather than append to, the server-level chain. Include all required error handling, validation and other middleware explicitly; see the complete service-scoped example.
Install and configure
Use Usage and chain composition for installation and middleware assembly, then the focused interceptor pages in the sidebar. The generated API owns exact factory signatures and option fields.