Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Mar 27, 2025

Maintenance ModeYou are viewing Amplify Gen 1 documentation. Amplify Gen 1 has entered maintenance mode and will reach end of life on May 1, 2027. New project should use Amplify Gen 2. For existing Gen 1 projects, a migration guide and tooling are available to help you upgrade. Switch to the latest Gen 2 docs →

サーバーサイドレンダリング

サーバーサイドレンダリングでAmplifyカテゴリーAPIを使用する

Amplify JS v6は、SSR対応フレームワークで構築されたフルスタックWebアプリのサーバー側から呼び出すことができるAPIセットを提供します。これらのAPIは、クロスリクエストの状態汚染を回避するために、分離されたサーバーコンテキスト内で呼び出す必要があります。分離されたサーバーコンテキストは、受信リクエストから抽出された情報を含み、APIコールによって使用されます。例えば、リクエストクッキーヘッダーから抽出されたAmplify Authトークンなどです。AmplifyのAPIがAuthトークンを取得し、さらにサービスコールのための認証情報を取得できるようにするには、tokenProvidercredentialsProviderを提供する必要があります(詳細は以下のセクションを参照してください)。

runWithAmplifyServerContext関数(aws-amplify/adapter-coreからエクスポート)を使用してサーバーコンテキストを作成する必要があります。この関数は、サーバーに送信されたクッキーに基づいてサーバーコンテキストを作成します。したがって、使用しているSSRフレームワークがリクエスト受信時とレスポンス送信時にクッキーと対話できるAPIを提供している場合、runWithAmplifyServerContext関数を使用してサーバー上でAmplifyカテゴリーAPIを呼び出すことができます。

注記: アプリのクライアント側でAmplify.configure()を呼び出す際に、ssrtrueに設定する必要があります。例えば、Amplify.configure(config, { ssr: true })のようにして、サーバーに送信されるリクエストがクッキーヘッダーにAmplify認証トークンを含むようにしてください。

アプリケーションのライフサイクルの早い段階でAmplify.configureを呼び出すようにしてください。Amplify.configureが他のAmplify JavaScript APIの前に呼び出されていない場合、設定がないかNoCredentialsエラーがスローされます。この問題の考えられる原因については、ライブラリが設定されていないトラブルシューティングガイドを確認してください。

runWithAmplifyServerContext関数の使用

runWithAmplifyServerContext関数は、機能するために以下のパラメータが必要です:

  1. Amplify設定オブジェクト
  2. tokenProvidercredentialsProviderプロパティを持つLibraryOptionsオブジェクト
  3. AmplifyカテゴリーAPIの呼び出しを含むビジネスロジックが含まれるコールバック関数

Amplify設定オブジェクト

amplifyconfiguration.jsonファイルからインポートされた設定オブジェクトをユーティリティ関数parseAmplifyConfigaws-amplify/utilsからエクスポート)に渡すことで設定オブジェクトを取得するか、ResourceConfig型(aws-amplifyからエクスポート)に準拠するオブジェクトリテラルを作成することができます。

tokenProvidercredentialsProviderプロパティを持つLibraryOptionsオブジェクト

上述したように、AmplifyカテゴリーAPIはAuthトークンと認証情報を取得するためにtokenProvidercredentialsProviderに依存します。したがって、以下のステップに従い、クッキーを使用してプロバイダーを作成および設定する必要があります。

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関数によって返されます。

コールバック関数内で作成された変数、オブジェクト参照(例えばcontextSpecパラメータ)、またはビジネスロジックを外側のスコープにホイストしてはいけません。これはクロスリクエスト状態の汚染につながる可能性があります。

runWithAmplifyServerContextとAmplifyAPIはサーバー側でステートレスです。runWithAmplifyServerContextの各呼び出しは、Cognitoサービスから認証情報をリクエストする可能性があります。したがって、runWithAmplifyServerContextをループで呼び出したり、単一のリクエスト内で複数回呼び出したりすることは避けるべきです。

注記: runWithAmplifyServerContextの呼び出しを必要とするサーバーへの大量の同時リクエストが予想される場合、Cognitoサービスによってスローされるレート制限例外が発生する可能性があるため、制限の調整をリクエストできます。詳細はAmazon Cognitoのクォータドキュメントを参照してください。

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 object
const amplifyConfig = parseAmplifyConfig(config);
// Step 1 create the key-value storage
const 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 side
const 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
AuthfetchAuthSession
AuthfetchUserAttributes
AuthgetCurrentUser
API (GraphQL)generateClient
API (REST)GET
API (REST)POST
API (REST)PUT
API (REST)DEL
API (REST)HEAD
API (REST)PATCH
StoragegetUrl
StoragegetProperties
Storagelist
Storageremove
Storagecopy

その他の例

Amplify JS v6は、上述のアプローチに基づいてNext.js用に事前構築されたアダプタを提供します。runWithAmplifyServerContext関数の使用方法の詳細については、@aws-amplify/adapter-nextjsパッケージのソースコードを確認できます。

また、Nuxt 3プロジェクトのサーバー側でAmplifyカテゴリーAPIと対話するためにrunWithAmplifyServerContext関数を使用する方法について、はじめかたガイドも提供しています。詳細はNuxt 3からAmplifyカテゴリーAPIを使用するを参照してください。