Open8
Amplify Studio メールアドレス認証開発
目的
Amplify Studio 認証機能をページに組み込む
認証方法 - メールアドレス
参照
1. authentication デプロイ
の手順に従いメールのみ有効なauthenticatinoをデプロイする
2. withAuthenticator でページコンポーネントを囲む
のサイトを参考に Next.js 13 app/layout.tsx の RootLayoutを withAuthenticator で囲んだところ下記エラーが発生
File path:
./src/app/layout.tsx
- wait compiling...
- error ./src/app/layout.tsx
ReactServerComponentsError:
You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
Learn more: https://nextjs.org/docs/getting-started/react-essentials
,-[/Users/amonden/hitomio/n2-photo-apps_main/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js:1:1]
1 | import { computePosition, arrow as arrow$1 } from '@floating-ui/dom';
2 | export * from '@floating-ui/dom';
3 | import * as React from 'react';
4 | import { useLayoutEffect, useEffect } from 'react';
: ^^^^^^^^^
5 | import * as ReactDOM from 'react-dom';
6 |
7 | var index = typeof document !== 'undefined' ? useLayoutEffect : useEffect;
`----
The error was caused by importing '@aws-amplify/ui-react/dist/esm/index.mjs' in './src/app/layout.tsx'.
Maybe one of these should be marked as a client entry with "use client":
./src/app/layout.tsx
layoutの利用は一旦廃止して、任意のpage.tsxに適用する
"use client";
import { Amplify } from "aws-amplify";
import awsconfig from "../../aws-exports";
import { ContestCard } from "../../ui-components";
import { withAuthenticator } from "@aws-amplify/ui-react"; // 追加
Amplify.configure(awsconfig);
function Contests() {
return (
<>
<h1>コンテスト1件表示デモ</h1>
<ContestCard id="" />
</>
);
}
export default withAuthenticator(Contests); // 追加
認証フォームが表示された
3. Amplify UI Login Formのカスタマイズ
具体的には
export default withAuthenticator(Contests, {
components: {
Header: () => <div>ヘッダーです</div>,
SignIn: {
Header: () => <div>SignInヘッダーです</div>,
Footer: () => <div>SignInフッターです</div>,
},
SignUp: {
Header: () => <div>SignUpヘッダーです</div>,
Footer: () => <div>SignUpフッターです</div>,
},
Footer: () => <div>フッターです</div>,
},
}); // 認証で追加
とすると下記のように表示される。
その他のラベルはローカライズで対応可能。
4. その他
認証イベントの監視方法(Listener) 主にログ出力か
ログイン直後の状態変更管理 > signUpConfig コールバックで対応
export default withAuthenticator(Login, {
usernameAttributes: "email",
signUpConfig
});
5. Sign-out
どこかにサインアウトメニューなどを設置してクリックしたら下記を実行
import { Auth } from 'aws-amplify';
export async function signOut() {
try {
await Auth.signOut(); // または Auth.signOut({ global: true });
} catch (error) {
console.log('error signing out: ', error);
}
}
Signout(ログアウト) が効かない場合
API一覧