サーバーサイドレンダリング
サーバーサイドレンダリングでAmplifyカテゴリーAPIを使用する
Amplify JS v6は、SSR対応フレームワークで構築されたフルスタックWebアプリのサーバー側から呼び出すことができるAPIセットを提供します。これらのAPIは、クロスリクエストの状態汚染を回避するために、分離されたサーバーコンテキスト内で呼び出す必要があります。分離されたサーバーコンテキストは、受信リクエストから抽出された情報を含み、APIコールによって使用されます。例えば、リクエストクッキーヘッダーから抽出されたAmplify Authトークンなどです。AmplifyのAPIがAuthトークンを取得し、さらにサービスコールのための認証情報を取得できるようにするには、tokenProviderとcredentialsProviderを提供する必要があります(詳細は以下のセクションを参照してください)。
runWithAmplifyServerContext関数(aws-amplify/adapter-coreからエクスポート)を使用してサーバーコンテキストを作成する必要があります。この関数は、サーバーに送信されたクッキーに基づいてサーバーコンテキストを作成します。したがって、使用しているSSRフレームワークがリクエスト受信時とレスポンス送信時にクッキーと対話できるAPIを提供している場合、runWithAmplifyServerContext関数を使用してサーバー上でAmplifyカテゴリーAPIを呼び出すことができます。
runWithAmplifyServerContext関数の使用
runWithAmplifyServerContext関数は、機能するために以下のパラメータが必要です:
- Amplify設定オブジェクト
tokenProviderとcredentialsProviderプロパティを持つLibraryOptionsオブジェクト- AmplifyカテゴリーAPIの呼び出しを含むビジネスロジックが含まれるコールバック関数
Amplify設定オブジェクト
amplifyconfiguration.jsonファイルからインポートされた設定オブジェクトをユーティリティ関数parseAmplifyConfig(aws-amplify/utilsからエクスポート)に渡すことで設定オブジェクトを取得するか、ResourceConfig型(aws-amplifyからエクスポート)に準拠するオブジェクトリテラルを作成することができます。
tokenProviderとcredentialsProviderプロパティを持つLibraryOptionsオブジェクト
上述したように、AmplifyカテゴリーAPIはAuthトークンと認証情報を取得するためにtokenProviderとcredentialsProviderに依存します。したがって、以下のステップに従い、クッキーを使用してプロバイダーを作成および設定する必要があります。
1. フレームワークによって提供されるクッキーAPI上で動作するキー値ストレージを作成する。
aws-amplify/adapter-coreからエクスポートされたユーティリティ関数createKeyValueStorageFromCookieStorageAdapterを使用してストレージオブジェクトを作成できます。
2. キー値ストレージを使用してtokenProviderを作成する
aws-amplify/adapter-coreからエクスポートされたユーティリティ関数createUserPoolsTokenProviderを使用してtokenProviderを作成できます。
3. キー値ストレージを使用してcredentialsProviderを作成する
aws-amplify/adapter-coreからエクスポートされたユーティリティ関数createAWSCredentialsAndIdentityIdProviderを使用してcredentialsProviderを作成できます。
コールバック関数
ビジネスロジックを含むコールバック関数は、runWithAmplifyServerContext関数によってコンテキスト内で呼び出されます。コールバック関数にはcontextSpecパラメータが渡され、これを使用してaws-amplify/<category>/serverサブパスからエクスポートされたAmplifyカテゴリーAPIを呼び出すことができます。コールバック関数が完了すると、対応するサーバーコンテキストは破棄され、コールバック関数によって返された結果がrunWithAmplifyServerContext関数によって返されます。
runWithAmplifyServerContextとAmplifyAPIはサーバー側でステートレスです。runWithAmplifyServerContextの各呼び出しは、Cognitoサービスから認証情報をリクエストする可能性があります。したがって、runWithAmplifyServerContextをループで呼び出したり、単一のリクエスト内で複数回呼び出したりすることは避けるべきです。
3つの必須パラメータを準備すれば、サーバー側でAmplifyカテゴリーAPIの呼び出しを実行できます。例えば:
import { createKeyValueStorageFromCookieStorageAdapter, createUserPoolsTokenProvider, createAWSCredentialsAndIdentityIdProvider, runWithAmplifyServerContext} from 'aws-amplify/adapter-core';import { parseAmplifyConfig } from 'aws-amplify/utils';import { getCurrentUser } from 'aws-amplify/auth/server';
import config from './amplifyconfiguration.json';
// Get the Amplify configuration objectconst amplifyConfig = parseAmplifyConfig(config);
// Step 1 create the key-value storageconst keyValueStorage = createKeyValueStorageFromCookieStorageAdapter({ get(name) { const value = ...; // use framework cookie API to get the value by name // NOTE: When you call `Amplify.configure()` with `{ ssr: true }`, // the token cookie value strings are encoded. You need to decode // the value here if the framework cookie API does not decode the value // strings. For example, you can use `decodeURIComponent(value)` // to decode the value. return { name, value }; }, getAll() { return [...]; // use framework cookie API to get an array of { name, value } }, set(name, value) { // use framework cookie API to set a cookie // // you should implement this function if you need to update the // token cookies on the client side from the server side }, delete(name) { // use framework cookies API to delete a cookie }})
// Step 2 create the `tokenProvider`const tokenProvider = createUserPoolsTokenProvider( amplifyConfig.Auth, keyValueStorage);
// Step 3 create the `credentialsProvider`const credentialsProvider = createAWSCredentialsAndIdentityIdProvider( amplifyConfig.Auth, keyValueStorage);
// Call Amplify APIs in the callback function//// For example, calling the `getCurrentUser` API on the server sideconst welcomeMessage = await runWithAmplifyServerContext( amplifyConfig, { Auth: { tokenProvider, credentialsProvider } }, // The callback function that contains your business logic async (contextSpec) => { const { username } = await getCurrentUser(contextSpec);
return `Welcome ${username}!`; },);サーバーサイド使用でサポートされているAPI
サーバー上での使用をサポートするすべてのAPIは、aws-amplify/<category>/serverサブパスからエクスポートされます。サーバー側の使用例には、これらのサーバーAPI変種を使用する必要があり、サーバー側の使用例ではクライアントAPI変種を使用してはいけません。サーバーコンテキストでクライアント側APIを使用すると、ランタイムエラーが生成されます。
| カテゴリー | API |
|---|---|
| Auth | fetchAuthSession |
| Auth | fetchUserAttributes |
| Auth | getCurrentUser |
| API (GraphQL) | generateClient |
| API (REST) | GET |
| API (REST) | POST |
| API (REST) | PUT |
| API (REST) | DEL |
| API (REST) | HEAD |
| API (REST) | PATCH |
| Storage | getUrl |
| Storage | getProperties |
| Storage | list |
| Storage | remove |
| Storage | copy |
その他の例
Amplify JS v6は、上述のアプローチに基づいてNext.js用に事前構築されたアダプタを提供します。runWithAmplifyServerContext関数の使用方法の詳細については、@aws-amplify/adapter-nextjsパッケージのソースコードを確認できます。
また、Nuxt 3プロジェクトのサーバー側でAmplifyカテゴリーAPIと対話するためにrunWithAmplifyServerContext関数を使用する方法について、はじめかたガイドも提供しています。詳細はNuxt 3からAmplifyカテゴリーAPIを使用するを参照してください。