Skip to content
Build a serviceDocs 1.3.x

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

typescript
interceptors: [audit, stockTag]

audit and stockTag are created by the factories below. Their write callback appends to this log.

typescript
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

  1. audit: before
  2. stockTag: before
  3. handler: return 7 units
  4. stockTag: after (set header)
  5. audit: after (header = fixture)
Successful call
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

  1. audit: before
  2. stockTag: before
  3. handler: return 7 units
  4. stockTag: after (set header)
  5. audit: after (header = fixture)

Caller’s x-stock-source: fixture.

stockTag → audit · Return stock · OK

  1. stockTag: before
  2. audit: before
  3. handler: return 7 units
  4. audit: after (header = unset)
  5. stockTag: after (set header)

Caller’s x-stock-source: fixture.

audit only · Return stock · OK

  1. audit: before
  2. handler: return 7 units
  3. audit: after (header = unset)

Caller’s x-stock-source: (not set).

audit → stockTag · Throw NotFound · NotFound

  1. audit: before
  2. stockTag: before
  3. handler: throw NotFound

Caller’s x-stock-source: (not set).

stockTag → audit · Throw NotFound · NotFound

  1. stockTag: before
  2. audit: before
  3. handler: throw NotFound

Caller’s x-stock-source: (not set).

audit only · Throw NotFound · NotFound

  1. audit: before
  2. handler: 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.

bash
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:

typescript
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

typescript
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

typescript
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

typescript
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
Compose and select RPC interceptors Built-in and custom wrappers are selected by service scope and method filters, then wrap the handler through next with result and error handling on the return path. Compose the behavior NEXT RESULT Built-in chainError handling · validationResilience: opt in Custom wrappersBefore · after · catchTest behavior Method filteringPatterns · call kindsDynamic: custom wrapper Applied chainGlobal defaults OR service replacementError handler first · explicit policy order RPC handlerBusiness behavior
Composition and selection are separate: service options replace the global chain, while method filtering selects applicable wrappers. Each wrapper can act before next and on its result or error.

Start with the default chain ​

typescript
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
typescript
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
NeedRoute
Configure the supported chainBuilt-in interceptors
Add business-specific middlewareCustom interceptors
Apply behavior to selected services or methodsMethod filtering
Authenticate or authorize callsAuth and authz
Trace incoming or outgoing callsTracing
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.