> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> 既存の Auth0 Hooks のコードを Auth0 Actions のコードへ移行する方法を学びます。

# Hooks から Actions への移行

既存の Hooks を Actions に変換する際は、新しい Action を、その Hook の種類に対応するトリガーに関連付ける必要があります。以下の手順に従い、その中で示す対応関係を使用すれば、同じ機能を実現できます。

<div id="plan-your-migration">
  ## 移行を計画する
</div>

デプロイ済みのActionsは有効なHooksの後に実行されるため、Hooksを1つずつAuth0 Dashboardで変換することも、<Tooltip tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Management+API">Management API</Tooltip> を使用して一括で変換することもできます。

コードを変換した後、Actionを有効化し、Hookを無効化する必要があります。Actionの有効化とHookの無効化はすぐ続けて実行できますが、順序によっては、短時間だけ両方が実行されたり、どちらも実行されなかったりする可能性があります。

そのため、パイプラインは段階的に移行することをお勧めします。Hooksのコードを部分ごとにActionのコードへ変換し、ステージング環境でテストしてから、1つずつ本番環境に反映してください。有効なHooksはデプロイ済みのActionsより先に実行されるため、Actionsで別のロジックを構築・テストしている間も、一部のロジックはHooksに残しておけます。

<Card title="移行を計画する際のヒント">
  * コストの高い処理や一度しか実行してはならない処理が重複しないよう、フラグを使用してください。
  * 変更は、影響とトラフィックが最も少ない時間帯に実施してください。
  * [Auth0 Deploy CLI](/docs/ja-jp/deploy-monitor/deploy-cli-tool) を使用して、移行全体を一括または段階的にスクリプト化し、テストして、すばやく実装することを検討してください。
</Card>

<div id="understand-limitations">
  ## 制限事項を理解する
</div>

Actions は Hooks でできることの大半に対応していますが、移行を始める前に、いくつかの制限事項を把握しておく必要があります。 (注意: 移行中は Hooks と Actions の両方を同時に実行できます。)

* Actions では、<Tooltip tip="アクセストークン: API にアクセスするために使用される、不透明な文字列または JWT 形式の認可資格情報。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=access+tokens">アクセストークン</Tooltip> や API レスポンスのようなデータを、実行間で保持することはできません。
* Actions では、Hooks のように [Management API 用のアクセストークン](/docs/ja-jp/customize/rules/use-management-api) や [グローバル `auth0` オブジェクトへのアクセス](/docs/ja-jp/customize/actions/action-coding-guidelines#global-object) は利用できません。

制限事項の一覧については、[Actions Limitations](/docs/ja-jp/customize/actions/limitations) を参照してください。

<div id="convert-code">
  ## コードを変換する
</div>

Hook を Action に変換するには、Hook 固有のコードを Actions のコードに置き換える必要があります。このセクションでは、動作中の Hook を対応する Action に変換するために必要な作業について説明します。

<Card title="コード変換時のヒント">
  * 基本的には、Hooks 関数に渡されるオブジェクトの読み取り専用プロパティに相当するものを、Actions の `event` オブジェクトで探してください。
  * コードの作成には Auth0 Dashboard の Actions Code Editor を使用してください。エラーのハイライト表示や自動補完候補の提示に役立ちます。
  * 本番環境に移行する前に、新しい [Actions を十分にテストし](/docs/ja-jp/customize/actions/test-actions)、[ステージング環境またはテスト環境](/docs/ja-jp/get-started/auth0-overview/create-tenants/set-up-multiple-environments) で入念に確認してください。
</Card>

<div id="copy-hook-code-to-a-new-action">
  ### Hook のコードを新しい Action にコピーする
</div>

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Hook のコードを新しい Action にコピーし、Auth0 Dashboard の Actions Code Editor を使用することをお勧めします。これにより、コードに残っている問題を特定しやすくなります。
</Callout>

1. 本番テナントにログインし、変換したい Hook からコードをコピーします。
2. 非本番テナントに切り替え、[Auth0 Dashboard > Actions > Library](https://manage.auth0.com/#/select-tenant?path=/actions/library) に移動します。
3. **Build Custom** を選択し、次の操作を行います。

   * 変換する Hook の名前と一致する Action の **Name** を入力します。

   * **Trigger** で、適切なトリガーを選択します\*\*:\*\*

     | Hook の種類                    | Actions のトリガー          |
     | --------------------------- | ---------------------- |
     | Client Credentials Exchange | M2M/Client-Credentials |
     | Pre-User-Registration       | Pre User Registration  |
     | Post-User-Registration      | Post User Registration |
     | Post-Change-Password        | Post Change Password   |
     | Send Phone Message          | Send Phone Message     |

   * **Runtime** で **Node 18** を選択します。

   * **Create** を選択します。
4. Actions Code Editor のコードブロックで、変換したい Hook のコードを export された関数の下に貼り付けます。
5. コードを関数内に移しながら、この記事の残りの部分で説明されている変更を加えます。
   また、新しい Actions のトリガーに関連付けられた `event` オブジェクトについても確認してください。このガイドの後半にある [データへのアクセス方法を変更する](#change-how-data-is-accessed) セクションに進むと、関連ドキュメントへのリンクが表示されます。

<div id="change-the-function-declaration">
  ### 関数宣言を変更する
</div>

フックの関数はデフォルトエクスポートでエクスポートされますが、Actions の関数は名前付きエクスポートを使用します。変換する Hook の種類に応じて、使用する名前付きエクスポートも変わります。対応は次のとおりです。

| フックの種類                      | 名前付きエクスポート                      |
| --------------------------- | ------------------------------- |
| Client Credentials Exchange | `onExecuteCredentialsExchange`  |
| Pre-User Registration       | `onExecutePreUserRegistration`  |
| Post-User Registration      | `onExecutePostUserRegistration` |
| Post-Change Password        | `onExecutePostChangePassword`   |
| Send Phone Message          | `onExecuteSendPhoneMessage`     |

**変更前**

```javascript lines theme={null}
module.exports = async function myHooksFunction(){}
```

**変換後**

```javascript lines theme={null}
// Client Credentials Exchange
exports.onExecuteCredentialsExchange = async (event, api) => {}

// ユーザー登録前
exports.onExecutePreUserRegistration = async (event, api) => {}

// ユーザー登録後
exports.onExecutePostUserRegistration = async (event) => {}

// パスワード変更後
exports.onExecutePostChangePassword = async (event) => {}

// Send Phone Message
exports.onExecuteSendPhoneMessage = async (event) => {}
```

<div id="convert-dependencies">
  ### 依存関係を移行する
</div>

フックとActionsでは、依存関係はほぼ同じ方法で扱います。どちらも、依存関係をUIまたはManagement APIから個別に追加し、コード内で使用します。また、どちらでも`npm` Registryで利用可能な任意のパッケージを`require`できます。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  `npm`モジュールが最新バージョンでない場合は、今がアップデートの絶好の機会です。
</Callout>

1. Hookコード内の`require`文を検索します。
2. バージョン番号を削除し、その番号はメモしておきます。
3. 依存関係が[NodeJSのコアモジュール](https://github.com/nodejs/node/tree/master/lib)でない場合は、[Write Your First Action](/docs/ja-jp/customize/actions/write-your-first-action) の「Add a Dependency」セクションの手順に従って追加します。コアモジュールであれば、追加する必要はありません。
4. 見つかった`require`文を`function`宣言の外に移動します。

<div id="convert-secrets">
  ### シークレットを変換する
</div>

Hooks と Actions では、シークレットはほぼ同じように扱われます。どちらも、Secrets は UI または Management API を使って Hook/Action ごとに追加し、コード内で利用します。

Hooks のシークレットを Actions に変換するには、次の手順を実行します。

1. 作業中の Action に必要な値を控えておきます。
2. Action 内からアクセスする値ごとに Secret を追加します。追加方法については、[Write Your First Action](/docs/ja-jp/customize/actions/write-your-first-action) の **Add a Secret** セクションを参照してください。
3. コードを変換します。

**Before**

```javascript lines theme={null}
async function (user, context, cb) {
    const { SECRET_NAME } = context.webtask.secrets;

    // ... 追加のコード
}
```

**変更後**

```javascript lines theme={null}
async (event, api) => {
    const { SECRET_NAME } = event.secrets;

	// ... 追加のコード
};
```

フックと同様に、Auth0 は保存時にすべてのシークレットの値を暗号化します。

<div id="change-how-data-is-accessed">
  ### データへのアクセス方法を変更する
</div>

Hooks では、ユーザー、クライアント、リクエスト、そのほかのコンテキストデータに関する情報は、Hook 関数に渡される複数の引数に格納されています。Actions では、これらのデータは再構成され、`event` オブジェクトに移されています。多くのプロパティはそのまま移行されていますが、わかりやすくするために統合されたものもあります。

変換する Hook の種類によって、`event` オブジェクトの内容は異なります。

* [Client Credentials Exchange - Actions イベントオブジェクト](/docs/ja-jp/customize/actions/explore-triggers/machine-to-machine-trigger/credentials-exchange-event-object)
* [Post-Change Password - Actions イベントオブジェクト](/docs/ja-jp/customize/actions/explore-triggers/password-reset-triggers/post-change-password-trigger/post-change-password-event-object)
* [Post-User Registration - Actions イベントオブジェクト](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/post-user-registration-trigger/post-user-registration-event-object)
* [Pre-User Registration - Actions イベントオブジェクト](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/pre-user-registration-trigger/pre-user-registration-event-object)
* [Send Phone Message - Actions イベントオブジェクト](/docs/ja-jp/customize/actions/explore-triggers/mfa-notifications-trigger/send-phone-message-event-object)

**変換前**

```javascript lines theme={null}
async function (user, context, cb) {
	const clientId = context.clientID;
	const tenant = context.connection.tenant

	// ... 追加のコード
}
```

**変換後**

```javascript lines theme={null}
async (event, api) => {
	const clientId = event.client.client_id;
	const tenant = event.tenant.id;

	// ... 追加のコード
};
```

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Hooks の `context` オブジェクトとは異なり、`event` オブジェクトのプロパティに保存または変更されたデータは、後続の Actions には引き継がれません。Hook でこれらのプロパティにデータを設定してコア機能をトリガーしている場合は、Actions 間でデータを保持するために、[Machine to Machine](/docs/ja-jp/customize/actions/explore-triggers/machine-to-machine-trigger/credentials-exchange-api-object) および [Pre User Registration](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/pre-user-registration-trigger/pre-user-registration-api-object) の Actions Flows で利用できる `api` インターフェースを使用する必要があります。
</Callout>

<div id="convert-callbacks">
  ### コールバックを変換する
</div>

Hook での処理が完了したら、実行を完了するために `callback()` 関数を呼び出す必要があります。一方、Actions ではコールバックの仕組みを使用しないため、Actions 関数から `callback()` の呼び出しをすべて削除する必要があります。

以前、Client Credentials Exchange または Pre User Registration Hook で、リクエストを失敗させたりユーザーを更新したりするために `callback()` 関数を使用していた場合でも、Actions では新しい `api` インターフェースを通じて引き続きこれを行えます。

<div id="client-credentials-exchange">
  #### Client Credentials Exchange
</div>

Client Credentials Exchange Hook で access token に追加のクレームを設定していた場合:

```javascript lines theme={null}
// Client Credentials Exchange Hook
module.exports = function(client, scope, audience, context, cb) {
  var access_token = {};
  access_token.scope = scope;

  access_token['https://example.com/claim'] = 'bar';
  cb(null, access_token);
};
```

これで、Actionsの[Client Credentials Exchange API オブジェクト](/docs/ja-jp/customize/actions/explore-triggers/machine-to-machine-trigger/credentials-exchange-api-object)を使用できるようになりました：

```javascript lines theme={null}
// Client Credentials Exchange Action
exports.onExecuteCredentialsExchange = async (event, api) => {
  api.accessToken.setCustomClaim("https://example.com/claim", 'bar');  
};
```

<div id="pre-user-registration">
  #### Pre User Registration
</div>

Pre User Registration Hook で access token に追加のクレームを設定していた場合:

```javascript lines theme={null}
// Pre User Registration Hook
module.exports = function (user, context, cb) {
	if (user.app_metadata.condition === "success") {
      var response = {};
      response.user = { user_metadata: { favorite_color: "purple" } };
      // このHookは成功しました。次のHookに進みます。
	  return callback(null, response);
	}

	if (user.app_metadata.condition === "failure") {
		// このHookは失敗しました。エラーレスポンスでログインを停止します。
		return callback(new Error("Failure message"));
	}

	// ... 追加コード
};
```

これで、[Pre User Registration API Object](/docs/ja-jp/customize/actions/explore-triggers/signup-and-login-triggers/pre-user-registration-trigger/pre-user-registration-api-object)を使用できるようになりました:

```javascript lines theme={null}
// Pre User Registration Action（事前ユーザー登録）
exports.onExecutePreUserRegistration = async (event, api) => {
	if (event.user.app_metadata.condition === "success") {
		// このActionは成功しました。次のActionに進みます。
		api.user.setUserMetadata("favorite_color", "purple");
		return;
	}

	if (event.user.app_metadata.condition === "failure") {
		// このActionは失敗しました。エラーレスポンスで処理を停止します。
		return api.access.deny("Failure message");
	}

	// ... 追加のコード
};
```

<div id="complete-the-migration">
  ## 移行を完了する
</div>

新しいActionsのコードを作成してテストしたら、Actionを有効化し、Hookを無効化する必要があります。これら2つの作業は立て続けにすばやく行えますが、順序によっては、短時間だけ両方が実行されたり、どちらも実行されなかったりする可能性があります。有効なHooksはデプロイ済みのActionsより先に実行されるため、Actionsで別のロジックを構築してテストしている間も、一部のロジックをルールに残しておくことができます。
