メインコンテンツまでスキップ

ブラウザ側で使用するMomento Web SDK for JavaScript

Momento は 2 つの JavaScript SDK を提供しています: Node.js 用 のものと他の Web アプリケーション用のものです。 2 つの SDK は同一の API を備えているため、importステートメントを除いてコードは同じように見えますが、内部では、異なる JavaScript ランタイム環境で最適なパフォーマンスと互換性を実現するように構築されています。

a picture of abstract web strung between node.js nodes.

Node.js SDK はサーバー側のユースケースに最適です。 ただし、Momento Web SDK を使用すると、開発者はブラウザで実行され、Momento サービスと直接通信する JavaScriptのコードで作成できます。 これにより、ブラウザと Momento の間のVector Indexの呼び出しを仲介する独自の Web サービスを構築および運用する際の一般的なオーバーヘッドを回避できます。 また、Web トラフィックのホップが 1 つ少なくなることを意味するため、Web アプリケーションのパフォーマンスをさらに向上させることができます。 両方の長所を生かしたものです。

Web SDK は、他の Node.js 以外の JavaScript 環境でも使用できます。

Momento Web SDK は、npm パッケージ @gomomento/sdk-web から入手できます。

ソース コードは GitHub にあります: momentohq/client-sdk-javascript

要件

リソース

  • Momento Node.js チートシート: このチートシートは Node.js SDK を対象としていますが、Web SDK API は完全な互換性があります。
  • Web SDK Examples: Web SDK の使用方法を示す実際のサンプル プロジェクト
  • COMING SOON: 本番環境で使用するチップス: Web SDK での構成とエラー処理

ブラウザで使用する用の web SDKの使い方

API 呼び出しは Momento Node.js SDK と同一 ですが、import/require ステートメントは npm からの @gomomento/sdk-web パッケージを消費します。 @gomomento/sdk (Node.js SDK) の代わりに。

Web SDK のインポート ステートメントの例を次に示します。

import {CacheClient} from ‘@gomomento/sdk-web’;

ブラウザで使用するための認証情報

Web ブラウザを使用するアプリケーションが Momento サービスと通信するには、ブラウザに Momento authトークンを提供する必要があります。 推奨される方法は、ブラウザーセッションごとに有効期限が切れた資格情報を持つ Momento の使い捨てできるトークンを生成することです。 これにより、アプリはデータの侵害を心配することなくトークンを配布できるようになります。

ブラウザで使用する Momento の使い捨てできるトークンを作成するには、通常、"token vending machine" のコンポーネントが必要になります。

token vending machineは、静的 Web サイトである HTTP エンドポイントを備えた スタンドアロンなアプリケーション にすることができます。

もしくはNext.js チャット アプリの例 のようにWeb アプリケーションのサーバー側に埋め込まれたコンポーネントで処理するパターンもできます。

どちらの場合も、Node.js SDK を使用して Momento AuthClient をインスタンス化し、Momento コンソール 経由で生成されたスーパー ユーザー スコープを持つ API キーを組み込む必要があります。

new AuthClient({
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});

次に、generateDisposableToken API を使用して、ブラウザー側で使い捨てられるトークンを作成します。 これらのトークンの有効期間はデフォルトでは短く、1 時間以内に期限切れになります。

// Generate a disposable token with read-write access to a specific key in one cache
const oneKeyOneCacheToken = await authClient.generateDisposableToken(
DisposableTokenScopes.cacheKeyReadWrite('squirrels', 'mo'),
ExpiresIn.minutes(30)
);
if (oneKeyOneCacheToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to the "mo" key in the "squirrels" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneKeyOneCacheToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${oneKeyOneCacheToken.expiresAt.epoch()}`);
} else if (oneKeyOneCacheToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${oneKeyOneCacheToken.errorCode()}: ${oneKeyOneCacheToken.toString()}`
);
}

// Generate a disposable token with read-write access to a specific key prefix in all caches
const keyPrefixAllCachesToken = await authClient.generateDisposableToken(
DisposableTokenScopes.cacheKeyPrefixReadWrite(AllCaches, 'squirrel'),
ExpiresIn.minutes(30)
);
if (keyPrefixAllCachesToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to keys prefixed with "squirrel" in all caches!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${keyPrefixAllCachesToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${keyPrefixAllCachesToken.expiresAt.epoch()}`);
} else if (keyPrefixAllCachesToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${keyPrefixAllCachesToken.errorCode()}: ${keyPrefixAllCachesToken.toString()}`
);
}

// Generate a disposable token with read-only access to all topics in one cache
const allTopicsOneCacheToken = await authClient.generateDisposableToken(
TokenScopes.topicSubscribeOnly('squirrel', AllTopics),
ExpiresIn.minutes(30)
);
if (allTopicsOneCacheToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to all topics in the "squirrel" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allTopicsOneCacheToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${allTopicsOneCacheToken.expiresAt.epoch()}`);
} else if (allTopicsOneCacheToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${allTopicsOneCacheToken.errorCode()}: ${allTopicsOneCacheToken.toString()}`
);
}

// Generate a disposable token with write-only access to a single topic in all caches
const oneTopicAllCachesToken = await authClient.generateDisposableToken(
TokenScopes.topicPublishOnly(AllCaches, 'acorn'),
ExpiresIn.minutes(30)
);
if (oneTopicAllCachesToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to all topics in the "squirrel" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneTopicAllCachesToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${oneTopicAllCachesToken.expiresAt.epoch()}`);
} else if (oneTopicAllCachesToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${oneTopicAllCachesToken.errorCode()}: ${oneTopicAllCachesToken.toString()}`
);
}

DisposableTokenScope や認可のための権限オブジェクトを含む Momento トークンの詳細については、Auth API リファレンス を参照してください。

FAQ

ブラウザからのトラフィックは暗号化されていますか?
Momento サービスのすべてのトラフィックと同様、Web SDK は回線上で完全に暗号化されます。 さらに、SDK は TLS 1.2+ 暗号化を使用しています。