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.
サーバーサイドレンダリング
JavaScript Server SDKとJavaScript Client SDKを組み合わせて使用し、サーバー側レンダリングによる体験を実現します。
完全な例については、GitHub上のexperiment-node-serverデモアプリを参照してください。
インストール
JavaScript Server SDKとJavaScript Client SDKの両方をインストールします。
npm install --save @amplitude/experiment-js-client @amplitude/experiment-node-server
Server SDKの初期化
サーバーのスタートアップ時に、Server SDKを初期化します。この例では、Client SDKのExperimentオブジェクトと区別するために、Server SDKのExperimentオブジェクトをExperimentServerとエイリアス化しています。
let ExperimentServer;
if (typeof window === 'undefined') {
console.debug('Initializing Server Experiment');
ExperimentServer = require('@amplitude/experiment-node-server').Experiment.initialize(
'server-IAxMYws9vVQESrrK88aTcToyqMxiiJoR',
{ debug: true },
);
}
export { ExperimentServer };
リクエストに応じてバリアントを取得する
各リクエストで、サーバー側のSDKを使用してバリアントを取得します。その結果、機能キーをvariant値にマップする単純なJavaScriptオブジェクトが作成されます。レンダリングコードがサーバー側とクライアント側の両方のコンテキストでアクセスできる場所に、結果を保存します。
const allFlags = await experimentServer.fetchV2({
id: 'userId',
});
// store the result where the rendering code can access it
global.appProps = { flags: allFlags };
レンダリング時にClient SDKを初期化する
サーバーサイドレンダリングを開始する際、取得したバリアントを使用してクライアント SDK を初期化します。 レンダリングスコープからアクセスできるExperimentClientをインスタンス化します(React ContextProvider経由など)。サーバー側のコンテキストでは、毎回新しいExperimentClientを作成します。クライアント側のコンテキストでは、存在しない場合にのみ新しいExperimentClientを作成します。
import { ExperimentClient } from '@amplitude/experiment-js-client';
let experimentClient;
const render = (appProps) => {
const isServerSide = typeof window === 'undefined';
if (isServerSide) {
console.debug('Initializing Client Experiment');
// on the server, create a new ExperimentClient every time
experimentClient = new ExperimentClient(
'client-IAxMYws9vVQESrrK88aTcToyqMxiiJoR',
{
initialVariants: appProps['features'],
},
);
} else if (!experiment) {
// in the client, only create the ExperimentClient once
experimentClient = Experiment.initialize(
'client-IAxMYws9vVQESrrK88aTcToyqMxiiJoR',
{
initialVariants: appProps['features'],
},
);
}
}
// use a provider or store the ExperimentClient so the render scope can access it
レンダリング時にバリアントを取得する
クライアントSDKを初期化した後、任意のコンポーネントのフラグステータスを取得します。
// experimentClient should be the same ExperimentClient instance from the previous step
experimentClient.variant('flag-key');
これは役に立ちましたか?