initializeEventIngestion
Initializes the event ingestion system with the specified configuration. This sets up the event provider, batching, and flush intervals.
Signature
function initializeEventIngestion(
eventsConfig: StudioConfig["events"]
): void
Parameters
eventsConfig
StudioConfig['events']
required
Configuration object for event ingestion
Whether event ingestion is enabled
Custom event provider implementation
clientType
'postgres' | 'prisma' | 'drizzle' | 'clickhouse' | 'https' | 'sqlite' | 'node-sqlite'
Type of database client
Table name for storing events
Events to batch before flushing
Flush interval in milliseconds
Usage Example
import { initializeEventIngestion, createPostgresProvider } from "better-auth-studio";
import { pool } from "./db";
initializeEventIngestion({
enabled: true,
client: pool,
clientType: "postgres",
tableName: "auth_events",
batchSize: 20,
flushInterval: 3000
});
Notes
- Can only be initialized once. Subsequent calls are ignored if already initialized
- Automatically creates the appropriate provider based on
clientType
- Sets up periodic event flushing when
batchSize > 1
emitEvent
Emits an authentication event to the configured ingestion provider. Events can be sent immediately or batched depending on configuration.
Signature
async function emitEvent(
type: AuthEventType,
data: {
status: "success" | "failed";
userId?: string;
sessionId?: string;
organizationId?: string;
metadata?: Record<string, any>;
request?: {
headers: Record<string, string>;
ip?: string
};
},
eventsConfig?: StudioConfig["events"]
): Promise<void>
Parameters
The type of authentication event (e.g., "user.joined", "user.logged_in", "oauth.linked")
Event data payload
status
'success' | 'failed'
required
Whether the event represents a successful or failed operation
ID of the user associated with this event
ID of the session associated with this event
ID of the organization associated with this event
Additional metadata specific to the event type (e.g., email, name, provider)
Request context information
HTTP headers from the request
Optional events configuration. If provided and ingestion is not initialized, it will be initialized with this config
Usage Example
import { emitEvent } from "better-auth-studio";
// Emit a successful login event
await emitEvent("user.logged_in", {
status: "success",
userId: "user_123",
sessionId: "session_456",
metadata: {
email: "[email protected]",
name: "John Doe"
},
request: {
headers: { "user-agent": "Mozilla/5.0..." },
ip: "192.168.1.1"
}
});
// Emit a failed login attempt
await emitEvent("user.logged_in", {
status: "failed",
metadata: {
email: "[email protected]",
reason: "Invalid credentials"
},
request: {
headers: { "user-agent": "Mozilla/5.0..." },
ip: "192.168.1.1"
}
});
Event Filtering
Events can be filtered using include and exclude configuration:
// Only track specific events
await emitEvent("user.joined", data, {
enabled: true,
include: ["user.joined", "user.logged_in"],
// ... other config
});
// Exclude certain events
await emitEvent("session.created", data, {
enabled: true,
exclude: ["session.created"],
// ... other config
});
getEventIngestionProvider
Returns the currently active event ingestion provider, or null if not initialized.
Signature
function getEventIngestionProvider(): EventIngestionProvider | null
Returns
provider
EventIngestionProvider | null
The active event ingestion provider instance, or null if not initialized
Usage Example
import { getEventIngestionProvider } from "better-auth-studio";
const provider = getEventIngestionProvider();
if (provider) {
// Query recent events
const result = await provider.query?.({
limit: 100,
sort: "desc"
});
console.log("Recent events:", result?.events);
}
checkEventIngestionHealth
Checks the health status of the event ingestion system.
Signature
async function checkEventIngestionHealth(): Promise<boolean>
Returns
true if the event ingestion system is healthy and operational, false otherwise
Usage Example
import { checkEventIngestionHealth } from "better-auth-studio";
const isHealthy = await checkEventIngestionHealth();
if (!isHealthy) {
console.error("Event ingestion system is unhealthy!");
}
Notes
- Returns
false if no provider is initialized
- If the provider implements a custom
healthCheck() method, it will be called
- Otherwise, returns
true if a provider is initialized
shutdownEventIngestion
Gracefully shuts down the event ingestion system, flushing any pending events and cleaning up resources.
Signature
async function shutdownEventIngestion(): Promise<void>
Usage Example
import { shutdownEventIngestion } from "better-auth-studio";
// During application shutdown
process.on("SIGTERM", async () => {
console.log("Shutting down event ingestion...");
await shutdownEventIngestion();
process.exit(0);
});
Behavior
- Sets a shutdown flag to prevent new events from being queued
- Clears any active flush timers
- Flushes all pending events in the queue
- Calls the provider’s
shutdown() method if implemented
- Resets all internal state (provider, config, queue, initialized flag)
Notes
- Always call this during application shutdown to prevent data loss
- Waits for all pending events to be flushed before completing
- Safe to call even if not initialized
Additional Exports
isEventIngestionInitialized
Checks whether the event ingestion system has been initialized.
function isEventIngestionInitialized(): boolean
getEventQueueSize
Returns the current number of events in the queue waiting to be flushed.
function getEventQueueSize(): number
Usage:
import { getEventQueueSize } from "better-auth-studio";
const queueSize = getEventQueueSize();
console.log(`${queueSize} events pending`);