🏃

Next.js SSR を Amplify で公開する手順

2024/02/23に公開

🎯目的

Next.js SSR を Amplify に公開できるようにする

💡前提

🏃手順

1. Amplify ホスティングを開始する

すべてのアプリ | AWS Amplify を開いて、「Amplify ホスティング」 > 「使用を開始する」を押してください。

2. ビルドイメージを変更する

ここまでで一度デプロイを開始してください。そうすると、2024年2月現在では構築時にエラーになるかと思います。

2024-02-22T14:07:52.254Z [WARNING]: You are using Node.js 16.19.0. For Next.js, Node.js version >= v18.17.0 is required.
2024-02-22T14:07:52.262Z [ERROR]: !!! Build failed
2024-02-22T14:07:52.263Z [INFO]: Please read more about Amplify Hosting's support for SSR frameworks to find if your build failure is related to an unsupported feature: https://docs.aws.amazon.com/amplify/latest/userguide/amplify-ssr-framework-support.html. You may also find this troubleshooting guide useful: https://docs.aws.amazon.com/amplify/latest/userguide/troubleshooting-ssr-deployment.html
2024-02-22T14:07:52.263Z [ERROR]: !!! Error: Command failed with exit code 1

これはビルド環境では、 Node.js のバージョンが 16 系になっていますが、Next.js では 18.17.0 以上の Node.js を指定する必要があるというエラーです。そのため、「アプリの設定」 > 「ビルドの設定」画面の「Build image settings」の構築イメージを変更します。

📝補足

環境変数を設定する

環境変数を設定する場合は、「アプリの設定」 > 「環境変数」を選択し、環境変数を追加します。

その後、「アプリの設定」 > 「ビルドの設定」を選択し、「アプリケーション構築の仕様」にて以下のように編集します。

下記の例では、環境変数 DB_HOST, DB_USER, DB_PASS をアプリで使えるようにする例です。

amplify.yml
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
+       - env | grep -e DB_HOST -e DB_USER -e DB_PASS >> .env.production
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - .next/cache/**/*
      - node_modules/**/*

独自ドメインで公開する

この例では、AWS Route 53 で購入した独自ドメインを Amplify に設定する方法を紹介します。

🔗APPENDIX

https://docs.aws.amazon.com/ja_jp/amplify/latest/userguide/deploy-nextjs-app.html

https://zenn.dev/yhi/scraps/e82a5fab5976e4

https://qiita.com/ssugimoto/items/61af44e94cfe961dd1ac

https://docs.aws.amazon.com/ja_jp/amplify/latest/userguide/ssr-environment-variables.html

Discussion