AWS Amplifyを使用して次のプロジェクトを配備(SSR)


nextプロジェクトをAWSに導入するには、さまざまな方法があります.
S 3またはEC 2に配備してもよい.
S 3に配備された場合、作成されたファイルが静的ファイルとして配布されるため、SSRは適用されない.
ただし、配備がAmplifyの場合は、SSRをアップロード、構築、配備することで適用できます.
Amplifyのみを使用してフロントエンドサーバを配備するか、バックエンドサーバのみを配備することができます.
フロントとバックグラウンドサーバの導入手順を紹介します.
次に、以前のパブリケーションで作成したCognitoユーザープールをインポートし、使用します.
Amplify CLIのインストール
Amplify cliのインストールには12が必要です.xバージョン以上のノードと6.インストールされているnpmは、少なくともxバージョンでなければなりません.
> npm install -g @aws-amplify/cli
Amplify CLIインストールドキュメント
IAMユーザーの作成
Amplifyを導入するには、IAMユーザーでなければなりません.
端末にamplify configureコマンドを発行するか、AWSに直接接続することによってIAMユーザを作成することができる.(作成されている場合はスキップできます.)

vscode端末で上記の画像シーケンスを選択すると、AWSによるIAMユーザーの追加ページが開きます.




鍵は作成時にのみ表示またはダウンロードできますので、csvファイルをダウンロードして保存してください.鍵が分からない場合は、新しい出口鍵を作成する必要があります.
vscode端末で作成したアクセスキーとキーを入力し、AWSプロファイルをローカルで作成します.

Amplifyプロジェクトの初期化amplify initコマンドを実行してプロジェクトを作成します.

その他のプロパティはデフォルト値を受け入れる必要がありますが、分散ディレクトリパスは.nextに変更する必要があります.


IAMユーザーの追加時に作成したプロファイルまたはアクセスキーを使用して認証を行います.
(アクセスキーを使用しました.)

作業フォルダにamplifyフォルダとsrcフォルダを作成し、srcフォルダにaws-exportsを作成します.jsファイルの作成が完了しました.
AWS Amplifyによって作成されたアプリケーションを表示できます.

ユーザー認証の追加amplify add authコマンドを実行して、ユーザー認証を追加します.

これにより、AWS Cognitoに新しいユーザープールが作成されます.
ただし、以前にパブリケーションで作成したユーザー・プールを使用するため、amplify import authコマンドを実行して既存のユーザー・プールをインポートします.


Amplifyプロジェクトリソースの更新
ユーザー認証がローカルに追加されているため、amplify push authコマンドを実行してAmplifyプロジェクトにリソースを更新します.

ローカルアプリケーションとamplfiyアプリケーションのプロパティが同期されます.

aws-amperingパッケージのインストール
https://github.com/seomimi/nextapp/tree/awsamplify
> npm i aws-amplify

//pages/_app.tsx
import Amplify from 'aws-amplify';
import awsmobile from '../src/aws-exports';
Amplify.configure(awsmobile);
会員に加入する
//components/SignupForm.tsx
import { Auth } from 'aws-amplify';
Auth.signUp({ username: email, password, attributes: { email } })
    .then((response) => {
        console.log(response);
        alert('가입완료! 이메일 인증 후 로그인 하세요.');
    })
    .catch((error) => {
        console.log(error);
        if (error.code === 'UsernameExistsException') {
            alert('이미 가입 된 이메일입니다.');
        }
    });
ログイン
//components/LoginForm.tsx
import { Auth } from 'aws-amplify';
Auth.signIn(email, password)
    .then((response) => {
        setUserId(response.attributes.email);
    })
    .catch((error) => {
        if (error.message == 'User is not confirmed.') {
            alert('가입한 이메일을 인증해주세요.');
        } else if (error.message == 'Incorrect username or password.') {
            alert('이메일 또는 비밀번호가 틀렸습니다.');
        }
    });
ログアウト
//pages/index.tsx
import { Auth } from 'aws-amplify';
Auth.signOut()
    .then(() => setUserId(null))
    .catch((error) => console.log(error));
SSRの適用
更新時にログインしたメンバー情報をサーバ側にロードし、ログインを維持する機能を追加します.
//pages/_app.tsx
import Amplify from 'aws-amplify';
import awsmobile from '../src/aws-exports';
Amplify.configure({ ...awsmobile, ssr: true });
amplify構成にssr: trueを追加します.
//pages/index.tsx
import type { NextPage, GetServerSideProps } from 'next';
import { Auth, withSSRContext } from 'aws-amplify';
export const getServerSideProps: GetServerSideProps = async (context) => {
    const { Auth } = withSSRContext(context);
    const user = await Auth.currentUserInfo()
        .then((response: any) => {
            return response?.attributes.email || null;
        })
        .catch((error: Error) => {
            console.log(error);
            return null;
        });
    return { props: { user } };
};
ログイン後にリフレッシュすると、ログインが完全に保持されていることがわかります.

Amplify管理の追加(フロントエンド導入)amplify add hostingコマンドを実行して、バックエンドに管理リソースを追加します.

「AWS amplifiedホスティングのアップロード」ページが開きます.
ダウンジャケットにアップロードしたコードを持ってきますので、その前にダウンジャケットに提出してください




構築設定にbaseDirectoryがあります.nextに設定する必要があります.(後で変更可能)

コンストラクションを続行すると、バックエンドコンストラクション時にエラーが発生します.
エラーに関する情報は構築ログで確認できます.
[WARNING]: ✖ There was an error initializing your environment.
[INFO]: Failed to pull the backend.
[INFO]: auth headless is missing the following inputParams userPoolId, webClientId, nativeClientId
[INFO]: Error: auth headless is missing the following inputParams userPoolId, webClientId, nativeClientId
userPoolId、webclientId、nativeClientIdパラメータが不足しているため、環境変数に値を追加して構築した場合、このエラーは表示されません.(NativeClientIdはWebClientIdと同じ値を使用できます.)
Amplifyコンソール環境変数


セキュアな構築と導入が完了すると、提供されるドメインに接続できます.