Skip to main content

Custom Middleware

Middleware runs after PiiSanitizer (which is always first and cannot be removed). Each middleware can transform or drop events before they reach adapters.

import type { IMiddleware, SunglassesEvent, MiddlewareNext } from '@drakkar.software/sunglasses-core';

const myMiddleware: IMiddleware = {
name: 'AddAppVersion',
async process(event: SunglassesEvent, next: MiddlewareNext) {
// Drop internal events
if (event.event.startsWith('$internal_')) return null;
// Enrich the event
return next({ ...event, properties: { ...event.properties, app_version: '2.0' } });
},
};

SunglassesCore.create({ middleware: [myMiddleware], ... });

Rules​

  1. Never throw — return null to drop; the pipeline catches throws and treats them as drops
  2. Always spread when modifying — { ...event, properties: { ...event.properties } }
  3. Never log distinctId or user traits
  4. Call next(event) to continue the pipeline

Built-in middleware​

MiddlewarePurpose
PiiSanitizerAlways prepended — redacts PII
SamplingMiddlewareRandom volume reduction — see Sampling
FrequencyMiddlewareAttach event counts — see Frequency counting

Contributor guide​

See Middleware authoring for testing patterns.