こんにちは。
株式会社クラスアクト インフラストラクチャ事業部の大塚です。
今回はAmplifyを使って認証機能付きのReactアプリをデプロイしていきたいと思います。
※当方、インフラエンジニアのものです。フロントエンド等々は勉強中なので、細かいことは書けません。
あくまでもメモレベルのものとしてご認識頂ければ幸いです。
構築イメージ
手順
以下のコマンドを実行してReact+TypeScriptのプロジェクトを作成します。
Amplify経由でCognitoをデプロイする時に、AWS側がTypeScriptで色々作っているようで、こちらも最初からTSで作っている方が色々楽そうなので、そうしてます。
C:\Users\ohtsu\Documents\AWS\amplify-temp>>npm create vite@6.0.0 .
> npx
> cva .
√ Select a framework: » React
√ Select a variant: » TypeScript
Scaffolding project in C:\Users\ohtsu\Documents\AWS\amplify...
Done. Now run:
npm install
npm run dev
C:\Users\ohtsu\Documents\AWS\amplify-temp>>npm install
added 190 packages, and audited 191 packages in 11s
48 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
この状態でGithubのリポジトリにpushします。
C:\Users\ohtsu\Documents\AWS\amplify-temp>git add .
warning: in the working copy of '.gitignore', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'README.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'eslint.config.js', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'index.html', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'package-lock.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'package.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/App.css', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/index.css', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/App.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/main.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/vite-env.d.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'tsconfig.app.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'tsconfig.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'tsconfig.node.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'vite.config.ts', LF will be replaced by CRLF the next time Git touches it
C:\Users\ohtsu\Documents\AWS\amplify-temp>git commit -m "first push"
[ts-tmp 1e8d112] first push
12 files changed, 874 insertions(+), 2111 deletions(-)
rename src/{App.jsx => App.tsx} (89%)
rename src/{main.jsx => main.tsx} (64%)
create mode 100644 src/vite-env.d.ts
create mode 100644 tsconfig.app.json
create mode 100644 tsconfig.json
create mode 100644 tsconfig.node.json
rename vite.config.js => vite.config.ts (100%)
C:\Users\ohtsu\Documents\AWS\amplify-temp>git push --set-upstream origin ts-tmp
Enumerating objects: 21, done.
Counting objects: 100% (21/21), done.
Delta compression using up to 20 threads
Compressing objects: 100% (10/10), done.
Writing objects: 100% (14/14), 12.82 KiB | 6.41 MiB/s, done.
Total 14 (delta 5), reused 7 (delta 3), pack-reused 0
remote: Resolving deltas: 100% (5/5), completed with 4 local objects.
remote:
remote: Create a pull request for 'ts-tmp' on GitHub by visiting:
remote: https://github.com/ohtsuka-shota/amplify/pull/new/ts-tmp
remote:
To https://github.com/ohtsuka-shota/amplify
* [new branch] ts-tmp -> ts-tmp
branch 'ts-tmp' set up to track 'origin/ts-tmp'.
Amplifyを使ってAWS上にデプロイしていきます。




デプロイできましたら、ts-tmpという部分を押下します。

認証タブを押下すると、このプロジェクトに認証機能を追加したいときの手順が記載されているので、これを実行していきます。

実行していきます。5分位かかると思います。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npm create amplify@latest
> amplify-temp@0.0.0 npx
> create-amplify
✔ Where should we create your project? .
12:36:06 Installing devDependencies:
12:36:06 - @aws-amplify/backend
12:36:06 - @aws-amplify/backend-cli
12:36:06 - aws-cdk-lib@2.189.1
12:36:06 - constructs@^10.0.0
12:36:06 - typescript@^5.0.0
12:36:06 - tsx
12:36:06 - esbuild
12:36:06 Installing dependencies:
12:36:06 - aws-amplify
12:36:06 ✔ 12:38:50 DevDependencies installed
12:38:50 ✔ 12:39:08 Dependencies installed
12:39:08 ✔ 12:39:08 Template files created
12:39:08 Successfully created a new project!
12:39:08 Welcome to AWS Amplify!
12:39:08 - Get started by running npx ampx sandbox.
12:39:08 - Run npx ampx help for a list of available commands.
12:39:08 Amplify collects anonymous telemetry data about general usage of the CLI. Participation is optional, and you may opt-out by using npx ampx configure telemetry disable. To learn more about telemetry, visit https://docs.amplify.aws/react/reference/telemetry
このタイミングでローカルにamplifyというフォルダが新規で作成されていると思います。

またpackage.jsonにも色々追加されていることがわかります。
amplify/backendとかが追加されていますね。
{
"name": "amplify-temp",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"aws-amplify": "^6.15.3",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@aws-amplify/backend": "^1.16.1",
"@aws-amplify/backend-cli": "^1.8.0",
"@eslint/js": "^9.15.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"aws-cdk-lib": "^2.189.1",
"constructs": "^10.4.2",
"esbuild": "^0.25.6",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.12.0",
"tsx": "^4.20.3",
"typescript": "^5.8.3",
"typescript-eslint": "^8.15.0",
"vite": "^6.0.0"
}
}
以下のコマンドを実行します。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npx ampx sandbox
12:42:47 The region ap-northeast-1 has not been bootstrapped. Sign in to the AWS console as a Root user or Admin to complete the bootstrap process, then restart the sandbox.
12:42:47 If this is not the region you are expecting to bootstrap, check for any AWS environment variables that may be set in your shell or use --profile <profile-name> to specify a profile with the correct region.
Webブラウザが立ち上上がり、AWSの管理コンソールが開きます。
設定を初期化を押下します。

処理が開始されます。

以下のように処理が完了することを確認します。
※既に作成されていたりすると処理に失敗することがあるかと思いますが、基本大丈夫だと思います。処理に失敗した場合はCloudFormationの管理画面から処理内容を確認すると良いかと思います。

CloudFormationでCDKToolkitが作成されていることを確認します。

この状態で改めてnpx ampx sandboxを実行します。
実行すると、AWS上に色々環境がデプロイされます。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npx ampx sandbox
Amplify Sandbox
Identifier: ohtsu
Stack: amplify-amplifytemp-ohtsu-sandbox-aed45ad6df
Region: ap-northeast-1
To specify a different sandbox identifier, use --identifier
12:49:26 WARNING: Schema is using an @auth directive with deprecated provider 'iam'. Replace 'iam' provider with 'identityPool' provider.
12:49:26 ✔ Backend synthesized in 1.87 seconds
12:49:30 ✔ Type checks completed in 4.03 seconds
12:49:36 ✔ Built and published assets
12:53:12 ✔ Deployment completed in 216.614 seconds
12:53:12 AppSync API endpoint = https://fel2bz2elba5zbnftzudj6x7zu.appsync-api.ap-northeast-1.amazonaws.com/graphql
12:53:12 [Sandbox] Watching for file changes...
12:53:13 File written: amplify_outputs.json
Stopping the sandbox process. To delete the sandbox, run npx ampx sandbox delete
バッチ ジョブを終了しますか (Y/N)? Y
実行後、Cognitoを確認するとユーザプールが作成されていることがわかります。

当たり前ですが、ユーザは登録されていません。

Cloudformationを確認してみると、色々デプロイされていることがわかります。

またローカルにamplify_outputs.jsonが生成され、以下のような情報が記載されていることがわかります。※マスキングしてます。
{
"auth": {
"user_pool_id": "***",
"aws_region": "ap-northeast-1",
"user_pool_client_id": "***",
"identity_pool_id": "***",
"mfa_methods": [],
"standard_required_attributes": [
"email"
],
"username_attributes": [
"email"
],
"user_verification_types": [
"email"
],
"groups": [],
"mfa_configuration": "NONE",
"password_policy": {
"min_length": 8,
"require_lowercase": true,
"require_numbers": true,
"require_symbols": true,
"require_uppercase": true
},
"unauthenticated_identities_enabled": true
},
"data": {
"url": "***",
"aws_region": "ap-northeast-1",
"default_authorization_type": "AWS_IAM",
"authorization_types": [
"AMAZON_COGNITO_USER_POOLS"
],
"model_introspection": {
"version": 1,
"models": {
"Todo": {
"name": "Todo",
"fields": {
"id": {
"name": "id",
"isArray": false,
"type": "ID",
"isRequired": true,
"attributes": []
},
"content": {
"name": "content",
"isArray": false,
"type": "String",
"isRequired": false,
"attributes": []
},
"createdAt": {
"name": "createdAt",
"isArray": false,
"type": "AWSDateTime",
"isRequired": false,
"attributes": [],
"isReadOnly": true
},
"updatedAt": {
"name": "updatedAt",
"isArray": false,
"type": "AWSDateTime",
"isRequired": false,
"attributes": [],
"isReadOnly": true
}
},
"syncable": true,
"pluralName": "Todos",
"attributes": [
{
"type": "model",
"properties": {}
},
{
"type": "auth",
"properties": {
"rules": [
{
"allow": "public",
"provider": "iam",
"operations": [
"create",
"update",
"delete",
"read"
]
}
]
}
}
],
"primaryKeyInfo": {
"isCustomPrimaryKey": false,
"primaryKeyFieldName": "id",
"sortKeyFieldNames": []
}
}
},
"enums": {},
"nonModels": {}
}
},
"version": "1.4"
}
ui-reactをインストールしていきます。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npm install @aws-amplify/ui-react
npm warn ERESOLVE overriding peer dependency
npm warn While resolving: @aws-amplify/plugin-types@1.10.1
npm warn Found: @aws-sdk/types@3.821.0
npm warn node_modules/@aws-amplify/data-construct/node_modules/@aws-amplify/ai-constructs/node_modules/@aws-amplify/plugin-types/node_modules/@aws-sdk/types
npm warn
npm warn Could not resolve dependency:
npm warn peer @aws-sdk/types@"^3.734.0" from @aws-amplify/plugin-types@1.10.1
npm warn node_modules/@aws-amplify/data-construct/node_modules/@aws-amplify/ai-constructs/node_modules/@aws-amplify/plugin-types
npm warn @aws-amplify/plugin-types@"^1.10.1" from @aws-amplify/ai-constructs@1.5.3
npm warn node_modules/@aws-amplify/data-construct/node_modules/@aws-amplify/ai-constructs
npm warn ERESOLVE overriding peer dependency
npm warn While resolving: @aws-amplify/plugin-types@1.10.1
npm warn Found: @aws-sdk/types@3.821.0
npm warn node_modules/@aws-amplify/graphql-api-construct/node_modules/@aws-amplify/ai-constructs/node_modules/@aws-amplify/plugin-types/node_modules/@aws-sdk/types
npm warn
npm warn Could not resolve dependency:
npm warn peer @aws-sdk/types@"^3.734.0" from @aws-amplify/plugin-types@1.10.1
npm warn node_modules/@aws-amplify/graphql-api-construct/node_modules/@aws-amplify/ai-constructs/node_modules/@aws-amplify/plugin-types
npm warn @aws-amplify/plugin-types@"^1.10.1" from @aws-amplify/ai-constructs@1.5.3
npm warn node_modules/@aws-amplify/graphql-api-construct/node_modules/@aws-amplify/ai-constructs
added 64 packages, and audited 2626 packages in 15s
226 packages are looking for funding
run `npm fund` for details
1 low severity vulnerability
To address all issues, run:
npm audit fix
Run `npm audit` for details.
srcディレクトリ配下のmain.tsxとApp.tsxを編集します。
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import '@aws-amplify/ui-react/styles.css'
import { Amplify } from 'aws-amplify'
import outputs from '../amplify_outputs.json'
Amplify.configure(outputs)
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
import './App.css'
import { Authenticator } from '@aws-amplify/ui-react'
function App() {
return (
<Authenticator>
{({ signOut, user }) => (
<>
<div>
<h1>{user?.username}!</h1>
<p>認証されました</p>
<button
onClick={signOut}
>
Sign Out
</button>
</div>
</>
)}
</Authenticator>
)
}
export default App
ローカルでアプリを稼働させてみます。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npm run dev
> amplify-temp@0.0.0 dev
> vite
VITE v6.3.5 ready in 200 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show help
Webブラウザでアクセスすると以下のようなUIが表示されます。
Create Accountを押下します。

適当なメールアドレスとパスワードを入力します。


入力したメールアドレスにメールが飛んでくることを確認します。
コードを確認してUIに入力します。


アカウントが作成されたことを確認します。

Cognito側にも登録がされたことを確認します。

.gitignoreで以下の行を削除します。
この記載があると、amplify_output.jsonがGithubにpushされません。
amplify_outputs*
この状態でGithubにpushします。
C:\Users\ohtsu\Documents\AWS\amplify-temp>git add .
warning: in the working copy of '.gitignore', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'package-lock.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'package.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/App.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/main.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'amplify/auth/resource.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'amplify/backend.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'amplify/data/resource.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'amplify/package.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'amplify/tsconfig.json', LF will be replaced by CRLF the next time Git touches it
C:\Users\ohtsu\Documents\AWS\amplify-temp>git commit -m "add cognito"
[ts-tmp de8046e] add cognito
10 files changed, 41581 insertions(+), 2179 deletions(-)
create mode 100644 amplify/auth/resource.ts
create mode 100644 amplify/backend.ts
create mode 100644 amplify/data/resource.ts
create mode 100644 amplify/package.json
create mode 100644 amplify/tsconfig.json
C:\Users\ohtsu\Documents\AWS\amplify-temp>git push
Enumerating objects: 23, done.
Counting objects: 100% (23/23), done.
Delta compression using up to 20 threads
Compressing objects: 100% (12/12), done.
Writing objects: 100% (16/16), 228.36 KiB | 13.43 MiB/s, done.
Total 16 (delta 4), reused 9 (delta 1), pack-reused 0
remote: Resolving deltas: 100% (4/4), completed with 4 local objects.
To https://github.com/ohtsuka-shota/amplify
1e8d112..de8046e ts-tmp -> ts-tmp
Githubにamplify_outputs.jsonファイル含め更新分がアップロードされていることを確認します。
これがアップロードされていないと、バックエンドと連携できないというエラーでAmplifyでのデプロイに失敗します。

ログイン画面が表示されるので、ローカルで作成したユーザで認証が通るか確認します。

最後に環境を削除します。
ローカルで以下を実行します。
C:\Users\ohtsu\Documents\AWS\amplify-temp>npx ampx sandbox delete
✔ Are you sure you want to delete all the resources in your sandbox environment (This can't be undone)? y
14:19:30 [Sandbox] Deleting all the resources in the sandbox environment...
14:22:40 ✔ Deployment completed in 188.731 seconds
14:22:40 [Sandbox] Finished deleting.






