klaviyo-sdk-patterns
Apply production-ready Klaviyo SDK patterns for the klaviyo-api package. Use when implementing Klaviyo integrations, refactoring SDK usage, or establishing team coding standards for Klaviyo API calls. Trigger with phrases like "klaviyo SDK patterns", "klaviyo best practices", "klaviyo code patterns", "idiomatic klaviyo", "klaviyo wrapper".
What this skill does
# Klaviyo SDK Patterns
## Overview
Production-ready patterns for the `klaviyo-api` Node.js SDK: singleton sessions, type-safe wrappers, retry logic, pagination, and multi-tenant support.
## Prerequisites
- `klaviyo-api` package installed
- Completed `klaviyo-install-auth` setup
- TypeScript project with strict mode
## Instructions
### Step 1: Singleton Session Pattern
```typescript
// src/klaviyo/session.ts
import { ApiKeySession } from 'klaviyo-api';
let _session: ApiKeySession | null = null;
export function getSession(apiKey?: string): ApiKeySession {
if (!_session) {
const key = apiKey || process.env.KLAVIYO_PRIVATE_KEY;
if (!key) throw new Error('KLAVIYO_PRIVATE_KEY is required');
_session = new ApiKeySession(key);
}
return _session;
}
// For testing: reset the singleton
export function resetSession(): void {
_session = null;
}
```
### Step 2: Type-Safe API Wrapper
```typescript
// src/klaviyo/api.ts
import {
ApiKeySession,
ProfilesApi,
EventsApi,
ListsApi,
SegmentsApi,
CampaignsApi,
FlowsApi,
MetricsApi,
TemplatesApi,
CatalogsApi,
DataPrivacyApi,
WebhooksApi,
} from 'klaviyo-api';
import { getSession } from './session';
// Lazy-initialized API clients -- avoids creating unused clients
const apis = {
get profiles() { return new ProfilesApi(getSession()); },
get events() { return new EventsApi(getSession()); },
get lists() { return new ListsApi(getSession()); },
get segments() { return new SegmentsApi(getSession()); },
get campaigns() { return new CampaignsApi(getSession()); },
get flows() { return new FlowsApi(getSession()); },
get metrics() { return new MetricsApi(getSession()); },
get templates() { return new TemplatesApi(getSession()); },
get catalogs() { return new CatalogsApi(getSession()); },
get dataPrivacy() { return new DataPrivacyApi(getSession()); },
get webhooks() { return new WebhooksApi(getSession()); },
};
export default apis;
```
### Step 3: Error Handling Wrapper
```typescript
// src/klaviyo/errors.ts
export interface KlaviyoApiError {
status: number;
statusText: string;
errors: Array<{ id: string; code: string; title: string; detail: string }>;
retryAfter?: number;
}
export function parseKlaviyoError(error: any): KlaviyoApiError {
return {
status: error.status || 500,
statusText: error.statusText || 'Unknown Error',
errors: error.body?.errors || [{ id: '', code: 'unknown', title: 'Unknown', detail: error.message }],
retryAfter: error.headers?.['retry-after'] ? parseInt(error.headers['retry-after']) : undefined,
};
}
export async function safeCall<T>(
operation: () => Promise<T>,
context: string
): Promise<{ data: T | null; error: KlaviyoApiError | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err: any) {
const parsed = parseKlaviyoError(err);
console.error(`[Klaviyo] ${context} failed:`, {
status: parsed.status,
errors: parsed.errors.map(e => e.detail),
});
return { data: null, error: parsed };
}
}
```
### Step 4: Retry with Retry-After Header
```typescript
// src/klaviyo/retry.ts
export async function withRetry<T>(
operation: () => Promise<T>,
options = { maxRetries: 3, baseDelayMs: 1000 }
): Promise<T> {
for (let attempt = 0; attempt <= options.maxRetries; attempt++) {
try {
return await operation();
} catch (error: any) {
if (attempt === options.maxRetries) throw error;
const status = error.status;
// Only retry on 429 (rate limit) and 5xx (server errors)
if (status !== 429 && (status < 500 || status >= 600)) throw error;
// Honor Klaviyo's Retry-After header (seconds)
const retryAfter = error.headers?.['retry-after'];
const delay = retryAfter
? parseInt(retryAfter) * 1000
: options.baseDelayMs * Math.pow(2, attempt) + Math.random() * 500;
console.log(`[Klaviyo] Retry ${attempt + 1}/${options.maxRetries} in ${delay.toFixed(0)}ms`);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
```
### Step 5: Cursor-Based Pagination
```typescript
// src/klaviyo/pagination.ts
/**
* Auto-paginate any Klaviyo list endpoint.
* Klaviyo uses cursor-based pagination with `page[cursor]` param.
* Each page returns max 20 items (some endpoints allow up to 100).
*/
export async function* paginate<T>(
fetcher: (pageCursor?: string) => Promise<{
body: { data: T[]; links?: { next?: string } };
}>
): AsyncGenerator<T> {
let cursor: string | undefined;
do {
const response = await fetcher(cursor);
for (const item of response.body.data) {
yield item;
}
// Extract cursor from next link URL
const nextLink = response.body.links?.next;
if (nextLink) {
const url = new URL(nextLink);
cursor = url.searchParams.get('page[cursor]') || undefined;
} else {
cursor = undefined;
}
} while (cursor);
}
// Usage: iterate all profiles
// for await (const profile of paginate(cursor => profilesApi.getProfiles({ pageCursor: cursor }))) {
// console.log(profile.attributes.email);
// }
```
### Step 6: Multi-Tenant Factory
```typescript
// src/klaviyo/multi-tenant.ts
import { ApiKeySession, ProfilesApi, EventsApi, ListsApi } from 'klaviyo-api';
interface TenantApis {
profiles: ProfilesApi;
events: EventsApi;
lists: ListsApi;
}
const tenantCache = new Map<string, TenantApis>();
export function getApisForTenant(tenantId: string, apiKey: string): TenantApis {
if (!tenantCache.has(tenantId)) {
const session = new ApiKeySession(apiKey);
tenantCache.set(tenantId, {
profiles: new ProfilesApi(session),
events: new EventsApi(session),
lists: new ListsApi(session),
});
}
return tenantCache.get(tenantId)!;
}
```
## SDK Conventions
| Convention | Example |
|-----------|---------|
| Property casing | `firstName` (not `first_name`) |
| Response access | `response.body.data` (not `response.data`) |
| Payload structure | `{ data: { type: 'profile', attributes: { ... } } }` |
| Filter syntax | `equals(email,"[email protected]")` |
| Sort syntax | `'-datetime'` (descending), `'datetime'` (ascending) |
| Include relations | `{ include: ['lists'] }` |
## Error Handling
| Error | Status | Retryable | Solution |
|-------|--------|-----------|----------|
| Invalid API key | 401 | No | Check KLAVIYO_PRIVATE_KEY |
| Missing scope | 403 | No | Add required scope to API key |
| Validation error | 400 | No | Fix request payload |
| Rate limited | 429 | Yes | Honor Retry-After header |
| Server error | 500/503 | Yes | Retry with backoff |
| Conflict | 409 | No | Resource already exists; use update |
## Resources
- [klaviyo-api-node README](https://github.com/klaviyo/klaviyo-api-node/blob/main/README.md)
- [API Overview](https://developers.klaviyo.com/en/reference/api_overview)
- [API Versioning](https://developers.klaviyo.com/en/docs/api_versioning_and_deprecation_policy)
## Next Steps
Apply patterns in `klaviyo-core-workflow-a` for profile and list management.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.