On this page

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

セッションリプレイとセグメントの連携

セッションリプレイは他のアナリティクスプロバイダーをサポートしています。セグメントでインストルメントされたサイトにセッションリプレイを追加するには、次のオプションを使用します。

リプレイキャプチャイベント

Amplitudeは、セッションリプレイがセッションをキャプチャすると[Amplitude] Replay Capturedイベントを作成します。Amplitude はこのイベントを直接受信し、Segment はそれを転送しません。 このイベントがAmplitudeに表示されない場合は、Amplitudeサポートにお問い合わせください。

Amplitude(アクション)送信先

Amplitude(アクション)はセッションを自動的に追跡します。ユーザーが新しいセッションを開始すると、Amplitudeはユーザーのブラウザにanalytics_session_idクッキーを設定します。セグメントのソースミドルウェアを使用して、analytics_session_idへの変更をリッスンするように実装を設定します。

次のコードスニペットは、セグメントのAmplitude(アクション)連携を使用してセッションリプレイを設定し、analytics_session_idが変更されたときにセッションIDを更新します。

javascript
import * as sessionReplay from "@amplitude/session-replay-browser";
import { AnalyticsBrowser } from "@segment/analytics-next";
const segmentAnalytics = AnalyticsBrowser.load({
  writeKey: "segment-key",
});
const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment
const getStoredSessionId = () => {
 return cookie.get("analytics_session_id") || 0;
}
const user = await segmentAnalytics.user();
const storedSessionId = getStoredSessionId();
await sessionReplay.init(AMPLITUDE_API_KEY, {
  sessionId: storedSessionId,
  deviceId: user.anonymousId()
}).promise;
// Add middleware to check if the session id has changed,
// and update the session replay instance
segmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {
  const storedSessionId = getStoredSessionId();
  const nextSessionId = payload.obj.integrations['Actions Amplitude'].session_id || 0
  if (storedSessionId < nextSessionId) {
    cookie.set("analytics_session_id", nextSessionId);
    sessionReplay.setSessionId(nextSessionId);
  }
  next(payload);
});

Amplitude Classic送信先(デバイスモード)

このバージョンのAmplitude送信先は、Amplitude JavaScript SDK(5.2.2)をクライアントにインストールし、イベントを直接api.amplitude.comに送信します。

デバイスモード連携にはamplitude-js SDKが含まれているため、デフォルトでセッションを追跡します。同梱されている SDK バージョン (5.2.2) は、セッション変更に対するイベントを発行しません。 セッション ID が変更された場合にセッションリプレイを更新するために、Segment のミドルウェアを使用してください。

javascript
import * as sessionReplay from "@amplitude/session-replay-browser";
import { AnalyticsBrowser } from "@segment/analytics-next";
const segmentAnalytics = AnalyticsBrowser.load({
  writeKey: "segment-key",
});
const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment
const getAmpSessionId = () => {
  const sessionId = window.amplitude.getInstance().getSessionId();
  cookie.set("analytics_session_id", sessionId);
  return sessionId;
};
// Wait for the amplitude-js SDK to initialize,
// then initialize session replay with the correct device id and session id
window.amplitude.getInstance().onInit(() => {
  const sessionId = getAmpSessionId();
  sessionReplay.init(AMPLITUDE_API_KEY, {
    deviceId: window.amplitude.getInstance().options.deviceId,
    sessionId: getAmpSessionId(),
  });
});
// Add middleware to check if the session id has changed,
// and update the session replay instance
segmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {
  const nextSessionId = window.amplitude.getInstance().getSessionId();
  const storedSessionId = cookie.get("analytics_session_id") || 0;
  if (storedSessionId < nextSessionId) {
    cookie.set("analytics_session_id", nextSessionId);
    sessionReplay.setSessionId(nextSessionId);
  }
  next(payload);
});

Amplitude Classic送信先(クラウドモード)

このバージョンのAmplitude送信先はイベントをSegmentのバックエンドに送信し、バックエンドはそれらをAmplitudeに転送します。 クラウドモードの送信先は、デフォルトではセッションを追跡しません。 次の例に示すように、Browser SDKをシェルとして使用してセッションを管理し、セッションリプレイをプラグインとして使用します。

javascript
import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser";
import { AnalyticsBrowser } from "@segment/analytics-next";
const segmentAnalytics = AnalyticsBrowser.load({
  writeKey: "segment-key",
});
// A plugin must be added so that events sent through Segment will have
// session replay properties and the correct session id
const segmentPlugin = () => {
  return {
    name: "segment",
    type: "destination",
    execute: async (event) => {
      const properties = event.event_properties || {};
      segmentAnalytics.track(event.event_type, properties, {
        integrations: {
          Amplitude: {
            session_id: amplitude.getSessionId(),
          },
        },
      });
      return {
        code: 200,
        event: event,
        message: "OK",
      };
    },
  };
};
const AMPLITUDE_API_KEY = 'api-key' // must match that saved with Segment
// Add the session replay plugin first, then the segment plugin
await amplitude.add(sessionReplayPlugin()).promise;
await amplitude.add(segmentPlugin()).promise;
const user = await segmentAnalytics.user();
await amplitude.init(AMPLITUDE_API_KEY, {
  instanceName: 'session-replay',
  sessionTimeout: Number.MAX_SAFE_INTEGER,
  defaultTracking: false,
  deviceId: user.anonymousId()
}).promise;
amplitude.remove('amplitude');
// Events must be tracked through the shell Browser SDK to properly attach
// session replay properties
amplitude.track('event name')

デバイス ID とセッション ID の文字制限

セッションリプレイ ID の形式は <deviceId>/<sessionId>です。セッションリプレイは/を区切り文字として使用するため、deviceId値に/を含めることはできません。使用できる文字:a-z A-Z 0-9 _ - . | @ : =。セグメントのanonymousId()はUUIDを返しますが、この値は常にこれらの要件を満たしています。deviceIdにカスタム値を使用する場合は、許容される文字セットに従っていることを確認してください。追加の文字をリクエストする必要がある場合は、Amplitudeサポートまでお問い合わせください。

Segment連携のトラブルシューティング

インスタンスが空を返す場合、セグメントミドルウェアがAmplitude連携フィールドのpayload.obj.integrations['Actions Amplitude']値を設定していない可能性があります。この場合、次のsetTimeoutラッパーを追加して、フィールドに有効な値が入力されるようにしてください。

js
segmentAnalytics.addSourceMiddleware(({ payload, next, integrations }) => {
    const storedSessionId = getStoredSessionId()
    setTimeout(() => {
      ... // Rest of the Segment integrations code
    }, 0)
    next(payload)
});

Was this helpful?