@astralibx/email-analytics
v2.5.4
Published
Email analytics with event recording, aggregation, time-series, and querying
Downloads
1,694
Maintainers
Readme
@astralibx/email-analytics
Event-level email tracking with automatic daily aggregation and pre-built query APIs. Record individual send/deliver/bounce/open/click events, aggregate them into daily stats by account, rule, or template, and query time-series data through REST endpoints or the programmatic API.
Install
npm install @astralibx/email-analyticsPeer dependencies (install separately):
npm install mongoose expressQuick Start
import mongoose from 'mongoose';
import express from 'express';
import { createEmailAnalytics } from '@astralibx/email-analytics';
const conn = mongoose.createConnection('mongodb://localhost:27017/myapp');
const analytics = createEmailAnalytics({
db: { connection: conn, collectionPrefix: 'myapp_' },
options: {
eventTTLDays: 90,
timezone: 'Asia/Kolkata',
},
});
// Mount REST routes
const app = express();
app.use('/api/analytics', analytics.routes);
// Record an event programmatically
await analytics.events.record({
type: 'sent',
accountId: '507f1f77bcf86cd799439011',
recipientEmail: '[email protected]',
ruleId: '507f1f77bcf86cd799439012',
});
// Run daily aggregation
await analytics.aggregator.aggregateDaily();
// Query overview stats
const overview = await analytics.query.getOverview(
new Date('2025-01-01'),
new Date('2025-01-31'),
);Features
- Event Recording -- single and batch insert with automatic timestamps; supports
externalUserIdfor external system user tracking andchannelfor CTA attribution (whatsapp, telegram, sms, web, etc.) (docs) - Daily Aggregation -- rolls up raw events into per-day stats by account, rule, template, and overall (docs)
- Range Aggregation -- backfill or re-aggregate any date range (docs)
- Time-Series Queries -- overview, timeline (daily/weekly/monthly), per-account, per-rule, per-template (docs)
- Variant Analytics -- per-variant (subjectIndex/bodyIndex) performance stats via
GET /variantsendpoint for A/B test analysis (docs) - REST API -- endpoints with date-range query params, including
GET /channelsfor channel breakdown,GET /variantsfor variant performance, andPOST /trackfor public event ingestion with CORS (docs) - TTL Cleanup -- MongoDB TTL index auto-expires old events; manual purge also available (docs)
- Programmatic API -- use services directly without HTTP (docs)
- Error Handling -- typed error classes for validation, date range, and aggregation failures (docs)
Integration with Other Packages
Wire hooks from @astralibx/email-account-manager and @astralibx/email-rule-engine to automatically record analytics events. See the integration guide for full examples.
import { createEmailAccountManager } from '@astralibx/email-account-manager';
import { createEmailRuleEngine } from '@astralibx/email-rule-engine';
import { createEmailAnalytics } from '@astralibx/email-analytics';
const analytics = createEmailAnalytics({ db: { connection: conn } });
const accountManager = createEmailAccountManager({ db: { connection: conn } });
// Record events via rule engine hooks config
const ruleEngine = createEmailRuleEngine({
db: { connection: conn },
hooks: {
onSend: async ({ ruleId, ruleName, email, status }) => {
await analytics.events.record({
type: status === 'sent' ? 'sent' : 'failed',
accountId: '...', // from your send context
recipientEmail: email,
ruleId,
});
},
},
});Getting Started Guide
- Configuration — Set up database and timezone
- Event Recording — Record email events (sent, delivered, bounced, etc.)
- Aggregation — Aggregate events into queryable stats (must be scheduled via cron)
- Querying — Query aggregated stats by date range, account, rule, or template
- Integration — Wire analytics to email-rule-engine and email-account-manager hooks
Reference: API Routes | Programmatic API | Types | Error Handling
Important: Events must be aggregated before querying. Schedule
aggregateDaily()via cron (hourly recommended). Without aggregation, query endpoints return empty results.
Exported Types
// Core types
export type { EmailAnalyticsConfig } from './types/config.types';
export type { EmailEvent, CreateEventInput } from './types/event.types';
export type { DailyStats, AccountStats, RuleStats, TemplateStats, OverviewStats, TimelineEntry, VariantStats } from './types/stats.types';
// Constants
export { EVENT_TYPE, EVENT_CHANNEL, AGGREGATION_INTERVAL, STATS_GROUP_BY } from './constants';
export type { EventType, EventChannel, AggregationInterval, StatsGroupBy } from './constants';
// Errors
export { AlxAnalyticsError, ConfigValidationError, InvalidDateRangeError, AggregationError } from './errors';License
MIT
