segment-cdp
Segment Customer Data Platformに関する専門的なパターンを提供するスキルで、Analytics.jsやサーバーサイドトラッキング、Protocolsを用いたトラッキングプランの設計、IDの名寄せ、デスティネーションの設定、データガバナンスのベストプラクティスまでを網羅します。CDPの導入・運用において設計指針や実装パターンを即座に参照したい場合に活用できます。
description の原文を見る
Expert patterns for Segment Customer Data Platform including Analytics.js, server-side tracking, tracking plans with Protocols, identity resolution, destinations configuration, and data governance best practices.
SKILL.md 本文
Segment CDP
Segment Customer Data Platform のエキスパートパターン。Analytics.js、サーバー側トラッキング、Protocols を使用したトラッキングプラン、アイデンティティ解決、デスティネーション設定、およびデータガバナンスのベストプラクティスを含みます。
パターン
Analytics.js ブラウザ統合
Analytics.js を使用したクライアント側トラッキング。track、identify、page、group コールを含みます。anonymous ID は identify がユーザーと統合されるまで保持されます。
// Next.js - Analytics プロバイダーコンポーネント
// lib/segment.ts
import { AnalyticsBrowser } from '@segment/analytics-next';
export const analytics = AnalyticsBrowser.load({
writeKey: process.env.NEXT_PUBLIC_SEGMENT_WRITE_KEY!,
});
// 型付きイベントヘルパー
export interface UserTraits {
email?: string;
name?: string;
plan?: 'free' | 'pro' | 'enterprise';
createdAt?: string;
company?: {
id: string;
name: string;
};
}
export function identify(userId: string, traits?: UserTraits) {
analytics.identify(userId, traits);
}
export function track<T extends Record<string, any>>(
event: string,
properties?: T
) {
analytics.track(event, properties);
}
export function page(name?: string, properties?: Record<string, any>) {
analytics.page(name, properties);
}
export function group(groupId: string, traits?: Record<string, any>) {
analytics.group(groupId, traits);
}
// Analytics 用の React フック
// hooks/useAnalytics.ts
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { analytics, page } from '@/lib/segment';
export function usePageTracking() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
// ルート変更時にページビューをトラッキング
page(pathname, {
path: pathname,
search: searchParams.toString(),
url: window.location.href,
title: document.title,
});
}, [pathname, searchParams]);
}
// _app.tsx または layout.tsx での使用
function RootLayout({ children }) {
usePageTracking();
return <html>{children}</html>;
}
// コンポーネント内でのイベントトラッキング
function PricingButton({ plan }: { plan: string }) {
const handleClick = () => {
track('Plan Selected', {
plan_name: plan,
page: 'pricing',
source: 'pricing_page',
});
};
return <button onClick={handleClick}>Select {plan}</button>;
}
// 認証時に identify を実行
function onUserLogin(user: User) {
identify(user.id, {
email: user.email,
name: user.name,
plan: user.plan,
createdAt: user.createdAt,
});
track('User Signed In', {
method: 'email',
});
}
コンテキスト
- ブラウザトラッキング
- ウェブサイト分析
- クライアント側イベント
Node.js を使用したサーバー側トラッキング
@segment/analytics-node を使用した高性能サーバー側トラッキング。内部バッチ処理により非ブロッキング。バックエンドイベント、webhook、および機密データに必須です。
// lib/segment-server.ts
import { Analytics } from '@segment/analytics-node';
// 初回のみ初期化
const analytics = new Analytics({
writeKey: process.env.SEGMENT_WRITE_KEY!,
flushAt: 20, // フラッシュ前のバッチサイズ
flushInterval: 10000, // 10 秒ごとにフラッシュ
});
// 型付きサーバー側トラッキング
export interface ServerContext {
ip?: string;
userAgent?: string;
locale?: string;
}
export function serverIdentify(
userId: string,
traits: Record<string, any>,
context?: ServerContext
) {
analytics.identify({
userId,
traits,
context: {
ip: context?.ip,
userAgent: context?.userAgent,
locale: context?.locale,
},
});
}
export function serverTrack(
userId: string,
event: string,
properties?: Record<string, any>,
context?: ServerContext
) {
analytics.track({
userId,
event,
properties,
timestamp: new Date(),
context: {
ip: context?.ip,
userAgent: context?.userAgent,
},
});
}
// シャットダウン時にフラッシュ
export async function closeAnalytics() {
await analytics.closeAndFlush();
}
// API ルートでの使用
// app/api/webhooks/stripe/route.ts
export async function POST(req: Request) {
const event = await req.json();
switch (event.type) {
case 'checkout.session.completed':
const session = event.data.object;
serverTrack(
session.client_reference_id,
'Order Completed',
{
order_id: session.id,
total: session.amount_total / 100,
currency: session.currency,
payment_method: session.payment_method_types[0],
},
{ ip: req.headers.get('x-forwarded-for') || undefined }
);
// ユーザー属性も更新
serverIdentify(session.client_reference_id, {
total_spent: session.amount_total / 100,
last_purchase_date: new Date().toISOString(),
});
break;
case 'customer.subscription.created':
serverTrack(
event.data.object.metadata.user_id,
'Subscription Started',
{
plan: event.data.object.items.data[0].price.nickname,
amount: event.data.object.items.data[0].price.unit_amount / 100,
interval: event.data.object.items.data[0].price.recurring.interval,
}
);
break;
}
return new Response('ok');
}
// グレースフルシャットダウン
process.on('SIGTERM', async () => {
await closeAnalytics();
process.exit(0);
});
コンテキスト
- サーバー側トラッキング
- バックエンドイベント
- webhook 処理
トラッキングプランの設計
Object + Action ネーミング規約を使用してイベントスキーマを設計します。必須プロパティ、型、および検証ルールを定義します。Protocols に接続して適用します。
// トラッキングプラン定義(概念的な YAML 構造)
// これは Segment Protocols 設定にマップされます
/*
tracking_plan:
display_name: "MyApp Tracking Plan"
rules:
events:
- name: "User Signed Up"
description: "ユーザーが登録を完了"
rules:
required:
- signup_method
properties:
signup_method:
type: string
enum: [email, google, github]
referral_code:
type: string
utm_source:
type: string
- name: "Product Viewed"
description: "ユーザーが製品ページを閲覧"
rules:
required:
- product_id
- product_name
properties:
product_id:
type: string
product_name:
type: string
category:
type: string
price:
type: number
currency:
type: string
default: USD
- name: "Order Completed"
description: "ユーザーが購入を完了"
rules:
required:
- order_id
- total
- products
properties:
order_id:
type: string
total:
type: number
currency:
type: string
products:
type: array
items:
type: object
properties:
product_id: { type: string }
name: { type: string }
price: { type: number }
quantity: { type: integer }
identify:
traits:
- name: email
type: string
required: true
- name: name
type: string
- name: plan
type: string
enum: [free, pro, enterprise]
- name: company
type: object
properties:
id: { type: string }
name: { type: string }
*/
// 型安全性を備えた TypeScript 実装
// types/segment-events.ts
export interface TrackingEvents {
'User Signed Up': {
signup_method: 'email' | 'google' | 'github';
referral_code?: string;
utm_source?: string;
};
'Product Viewed': {
product_id: string;
product_name: string;
category?: string;
price?: number;
currency?: string;
};
'Order Completed': {
order_id: string;
total: number;
currency?: string;
products: Array<{
product_id: string;
name: string;
price: number;
quantity: number;
}>;
};
'Feature Used': {
feature_name: string;
usage_count?: number;
};
}
// 型安全な track 関数
export function trackEvent<T extends keyof TrackingEvents>(
event: T,
properties: TrackingEvents[T]
) {
analytics.track(event, properties);
}
// 使用例 - コンパイル時の型チェック
trackEvent('Order Completed', {
order_id: 'ord_123',
total: 99.99,
products: [
{ product_id: 'prod_1', name: 'Widget', price: 49.99, quantity: 2 },
],
});
// これは TypeScript エラーになります:
// trackEvent('Order Completed', { total: 99.99 }); // order_id がありません
コンテキスト
- トラッキングプラン
- データガバナンス
- イベントスキーマ
アイデンティティ解決
匿名ユーザーをトラッキングして、identify() 経由でユーザーと統合します。alias() を使用してシステム間のアイデンティティ統合を行います。ユーザーを企業/組織にグループ化します。
// アイデンティティフロー実装
// lib/identity.ts
// 匿名ユーザートラッキング
export function trackAnonymousAction(event: string, properties?: object) {
// Analytics.js が自動的に anonymousId を生成
analytics.track(event, properties);
}
// ユーザーがサインアップまたはログインしたとき
export async function identifyUser(user: {
id: string;
email: string;
name?: string;
plan?: string;
}) {
// これは匿名の履歴をユーザープロフィールと統合
await analytics.identify(user.id, {
email: user.email,
name: user.name,
plan: user.plan,
created_at: new Date().toISOString(),
});
// 識別イベントをトラッキング
analytics.track('User Identified', {
method: 'signup',
});
}
// B2B: ユーザーを企業に関連付け
export function associateWithCompany(company: {
id: string;
name: string;
plan?: string;
employees?: number;
industry?: string;
}) {
analytics.group(company.id, {
name: company.name,
plan: company.plan,
employees: company.employees,
industry: company.industry,
});
}
// Alias: アイデンティティをリンク(例:登録前メールを ユーザー ID にリンク)
export function linkIdentities(previousId: string, newUserId: string) {
// 一時的な ID でユーザーを識別し、
// 永続的なユーザー ID を入手した場合に使用
analytics.alias(newUserId, previousId);
}
// 完全なサインアップフロー
export async function handleSignup(
email: string,
password: string,
company?: { name: string; size: string }
) {
// 1. システムでユーザーを作成
const user = await createUser(email, password);
// 2. Segment で識別(匿名の履歴と統合)
await identifyUser({
id: user.id,
email: user.email,
name: user.name,
plan: 'free',
});
// 3. サインアップイベントをトラッキング
analytics.track('User Signed Up', {
signup_method: 'email',
plan: 'free',
});
// 4. B2B の場合、企業に関連付け
if (company) {
const companyRecord = await createCompany(company, user.id);
associateWithCompany({
id: companyRecord.id,
name: company.name,
employees: parseInt(company.size),
});
}
}
コンテキスト
- ユーザー識別
- 匿名トラッキング
- B2B トラッキング
デスティネーション設定
分析ツール、データウェアハウス、およびマーケティングプラットフォームへのデータルーティング。クライアント側ツールには device-mode、サーバー処理には cloud-mode を使用します。
// Segment デスティネーションは Segment UI で設定されます
// しかしここでは実装を最適化する方法を示します
// デスティネーション需要に基づく条件付きトラッキング
// lib/segment-destinations.ts
interface DestinationConfig {
mixpanel: boolean;
amplitude: boolean;
googleAnalytics: boolean;
warehouse: boolean;
hubspot: boolean;
}
// 特定のデスティネーションで必要なイベントのみを送信
export function trackWithDestinations(
event: string,
properties: Record<string, any>,
options?: {
integrations?: Partial<DestinationConfig>;
}
) {
analytics.track(event, properties, {
integrations: {
// 特定のデスティネーションをオーバーライド
All: true, // デフォルトではすべてに送信
...options?.integrations,
},
});
}
// 例:売上イベントを売上トラッキングデスティネーションのみに送信
export function trackRevenue(order: {
orderId: string;
total: number;
currency: string;
}) {
analytics.track('Order Completed', {
order_id: order.orderId,
revenue: order.total,
currency: order.currency,
}, {
integrations: {
// 売上デスティネーションを明示的に有効化
'Google Analytics 4': true,
'Mixpanel': true,
'Amplitude': true,
// 売上以外のデスティネーションを無効化
'Intercom': false,
'Zendesk': false,
},
});
}
// PII を安全なデスティネーションのみに送信
export function identifyWithPII(userId: string, traits: {
email: string;
phone?: string;
address?: string;
}) {
analytics.identify(userId, traits, {
integrations: {
'All': false, // デフォルトではすべて無効化
// 信頼できるデスティネーションのみに PII を送信
'HubSpot': true,
'Salesforce': true,
'Warehouse': true, // データウェアハウス
// 分析ツールに PII を送信しない
'Mixpanel': false,
'Amplitude': false,
},
});
}
// すべてのイベントに対するコンテキスト エンリッチメント
export function enrichedTrack(
event: string,
properties: Record<string, any>
) {
analytics.track(event, {
...properties,
// 共通のコンテキストを追加
app_version: process.env.NEXT_PUBLIC_APP_VERSION,
environment: process.env.NODE_ENV,
timestamp: new Date().toISOString(),
}, {
context: {
app: {
name: 'MyApp',
version: process.env.NEXT_PUBLIC_APP_VERSION,
},
},
});
}
コンテキスト
- データルーティング
- デスティネーション設定
- ツール統合
HTTP トラッキング API
任意の環境向けの直接 HTTP API。エッジファンクション、ワーカー、非 Node.js バックエンドに有用です。リクエスト当たり最大 500KB までバッチ処理可能。
// HTTP API 経由のエッジ/サーバーレストラッキング
// lib/segment-http.ts
const SEGMENT_WRITE_KEY = process.env.SEGMENT_WRITE_KEY!;
const SEGMENT_API = 'https://api.segment.io/v1';
// 認証用に write key を base64 エンコード
const authHeader = `Basic ${btoa(SEGMENT_WRITE_KEY + ':')}`;
interface SegmentEvent {
userId?: string;
anonymousId?: string;
event?: string;
name?: string; // page コール用
properties?: Record<string, any>;
traits?: Record<string, any>;
context?: Record<string, any>;
timestamp?: string;
}
async function segmentRequest(
endpoint: string,
payload: SegmentEvent
): Promise<void> {
const response = await fetch(`${SEGMENT_API}${endpoint}`, {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify({
...payload,
timestamp: payload.timestamp || new Date().toISOString(),
}),
});
if (!response.ok) {
console.error('Segment API エラー:', await response.text());
}
}
// HTTP API メソッド
export async function httpIdentify(
userId: string,
traits: Record<string, any>,
context?: Record<string, any>
) {
await segmentRequest('/identify', {
userId,
traits,
context,
});
}
export async function httpTrack(
userId: string,
event: string,
properties?: Record<string, any>,
context?: Record<string, any>
) {
await segmentRequest('/track', {
userId,
event,
properties,
context,
});
}
export async function httpPage(
userId: string,
name: string,
properties?: Record<string, any>
) {
await segmentRequest('/page', {
userId,
name,
properties,
});
}
// 高ボリューム用バッチ API
export async function httpBatch(
events: Array<{
type: 'identify' | 'track' | 'page' | 'group';
userId?: string;
anonymousId?: string;
event?: string;
name?: string;
properties?: Record<string, any>;
traits?: Record<string, any>;
}>
) {
// バッチ当たり最大 500KB、イベント当たり 32KB
await segmentRequest('/batch', {
batch: events.map(e => ({
...e,
timestamp: new Date().toISOString(),
})),
} as any);
}
// Cloudflare Worker の例
export default {
async fetch(request: Request): Promise<Response> {
const { userId, action, data } = await request.json();
// エッジファンクションでトラッキング
await httpTrack(userId, action, data, {
ip: request.headers.get('cf-connecting-ip'),
userAgent: request.headers.get('user-agent'),
});
return new Response('ok');
},
};
コンテキスト
- エッジファンクション
- サーバーレス
- HTTP トラッキング
注意点
匿名 ID は明示的なリセットまで保持される
重大度: MEDIUM
Device Mode は Protocols ブロッキングをバイパスする
重大度: HIGH
HTTP API には厳格なサイズ制限がある
重大度: MEDIUM
Identify なしの Track コールは匿名
重大度: HIGH
クライアント内の Write Key は表示されている(ただし意図的)
重大度: LOW
ページナビゲーション時にイベントが失われる可能性がある
重大度: MEDIUM
タイムゾーンなしのタイムスタンプは分析問題を引き起こす
重大度: MEDIUM
同意前のトラッキングは GDPR に違反する
重大度: HIGH
検証チェック
動的なイベント名
重大度: ERROR
イベント名は静的である必要があり、動的な値を含めてはいけません
メッセージ: 動的なイベント名が検出されました。静的なイベント名と動的なプロパティを使用してください。
イベント名のケース表記の不一致
重大度: WARNING
イベント名は一貫したケース表記規約に従う必要があります
メッセージ: イベント名にケース表記の混在があります。一貫した規約(例:Title Case)を使用してください。
Identify なしの Track
重大度: WARNING
ユーザーは重要なイベントをトラッキングする前に識別される必要があります
メッセージ: 識別なしの売上/コンバージョンイベント。ユーザーが識別されていることを確認してください。
ログアウト時に Analytics リセットがない
重大度: WARNING
ユーザーがログアウトしたときに Analytics をリセットしてください
メッセージ: analytics.reset() なしでログアウト。Anonymous ID が次のユーザーに保持されます。
ハードコードされた Segment Write Key
重大度: ERROR
Write Key は環境変数を使用する必要があります
メッセージ: ハードコードされた Segment write key。環境変数を使用してください。
すべてのデスティネーションに送信される PII
重大度: WARNING
PII はデスティネーション制御を備える必要があります
メッセージ: デスティネーション制御なしでトラッキングされた PII。デスティネーション制限を検討してください。
適切なタイムスタンプなしのイベント
重大度: INFO
明示的なタイムスタンプは履歴データに役立ちます
メッセージ: 明示的なタイムスタンプなしのサーバートラック。タイムスタンプを追加することを検討してください。
潜在的に大きいプロパティ値
重大度: WARNING
32KB を超えるプロパティは拒否されます
メッセージ: 潜在的に大きいプロパティ値。Segment にはイベント当たり 32KB の制限があります。
同意チェック前のトラッキング
重大度: ERROR
GDPR はトラッキング前に同意を要求します
メッセージ: 同意チェックなしでトラッキング。GDPR コンプライアンスのため同意管理を実装してください。
コラボレーション
デリゲーション トリガー
- ユーザーが A/B テストを必要とする -> analytics-specialist (Segment + LaunchDarkly/Optimizely 統合)
- ユーザーがデータウェアハウスを必要とする -> data-engineer (Segment から BigQuery/Snowflake/Redshift)
- ユーザーが顧客サポート統合を必要とする -> zendesk-integration (サポートツールに同期する Identify コール)
- ユーザーがマーケティング自動化を必要とする -> hubspot-integration (Segment から HubSpot デスティネーション)
- ユーザーが同意管理を必要とする -> privacy-specialist (Segment での GDPR/CCPA コンプライアンス)
使用すべき場合
- ユーザーが以下を言及または示唆した場合: segment
- ユーザーが以下を言及または示唆した場合: analytics.js
- ユーザーが以下を言及または示唆した場合: customer data platform
- ユーザーが以下を言及または示唆した場合: cdp
- ユーザーが以下を言及または示唆した場合: tracking plan
- ユーザーが以下を言及または示唆した場合: event tracking
- ユーザーが以下を言及または示唆した場合: identify track page
- ユーザーが以下を言及または示唆した場合: data routing
制限事項
- このスキルは、上記に説明されているスコープと明らかに一致するタスクの場合のみ使用してください。
- 出力を環境固有の検証、テスト、またはエキスパートレビューの代替物として扱わないでください。
- 必須入力、パーミッション、安全境界、または成功基準が不足している場合は、停止して明確化を求めてください。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- sickn33
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/sickn33/antigravity-awesome-skills / ライセンス: MIT
関連スキル
hugging-face-trackio
Trackioを使用してMLトレーニング実験を追跡・可視化できます。トレーニング中のメトリクスログ記録(Python API)、トレーニング診断のアラート発火、ログされたメトリクスの取得・分析(CLI)が必要な場合に活用してください。リアルタイムダッシュボード表示、Webhookを使用したアラート、HF Space同期、自動化向けのJSON出力に対応しています。
btc-bottom-model
ビットコインのサイクルタイミングモデルで、加重スコアリングシステムを搭載しています。日次パルス(4指標、32ポイント)とウィークリー構造(9指標、68ポイント)の2カテゴリーにわたる13の指標を追跡し、0~100のマーケットヒートスコアを算出します。ETFフロー、ファンディングレート、ロング/ショート比率、恐怖・貪欲指数、LTH-MVRV、NUPL、SOPR(LTH+STH)、LTH供給率、移動平均倍率(365日MA、200週MA)、週次RSI、出来高トレンドに対応します。市場サイクル全体を通じて買いと売りの両方の推奨を提供します。ビットコインの底値拾い、BTCサイクルポジション、買い時・売り時、オンチェーン指標、MVRV、NUPL、SOPR、LTH動向、ETFの流出入、ファンディングレート、恐怖指数、ビットコインが過熱状態か、マイナーコスト、暗号資産市場のセンチメント、BTCのポジションサイジング、「今ビットコインを買うべきか」「BTCが天井をつけているか」「オンチェーン指標は何を示しているか」といった質問の際にこのスキルを活用します。
protein_solubility_optimization
タンパク質の溶解性最適化 - タンパク質の溶解性を最適化します。タンパク質の特性を計算し、溶解性と親水性を予測し、有効な変異を提案します。タンパク質配列の特性計算、タンパク質機能の予測、親水性計算、ゼロショット配列予測を含むタンパク質エンジニアリング業務に使用できます。3つのSCPサーバーから4つのツールを統合しています。
research-lookup
Parallel Chat APIまたはPerplexity sonar-pro-searchを使用して、最新の研究情報を検索できます。学術論文の検索にも対応しています。クエリは自動的に最適なバックエンドにルーティングされるため、論文の検索、研究データの収集、科学情報の検証に活用できます。
tree-formatting
ggtree(R)またはiTOL(ウェブ)を使用して、系統樹の可視化とフォーマットを行います。系統樹を図として描画する際、ツリーレイアウトの選択、分類学に基づく枝やラベルの色付け、クレードの折りたたみ、サポート値の表示、またはツリーへのオーバーレイ追加が必要な場合に使用してください。系統推定(protein-phylogenyスキルを使用)やドメイン注釈(今後の独立したスキル)には使用しないでください。
querying-indonesian-gov-data
インドネシア政府の50以上のAPIとデータソースに接続できます。BPJPH(ハラール認証)、BOM(食品安全)、OJK(金融適正性)、BPS(統計)、BMKG(気象・地震)、インドネシア中央銀行(為替レート)、IDX(株式)、CKAN公開データポータル、pasal.id(第三者法MCP)に対応しています。インドネシア政府データを活用したアプリ開発、.go.idウェブサイトのスクレイピング、ハラール認証の確認、企業の法的適正性の検証、金融機関ステータスの照会、またはインドネシアMCPサーバーへの接続時に使用できます。CSRF処理、CKAN API使用方法、IP制限回避など、すぐに実行可能なPythonパターンを含んでいます。