🐥

さくっと amplify を使って Next.js をホスティングする

に公開

この記事は mob Advent Calendar 2日目の記事になります。

今回は amplify を使って、サクッと Next.js のアプリケーションを SSGモードでホスティングする方法を説明します。

前提

  • すでに実装してる Next.js のアプリケーションがある
  • AWSのアカウントがある
  • Amplify CLI をインストールして、amplify configure が完了している

next.config.js を用意

まずは 下記 next.config.js を準備します。

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
};

module.exports = nextConfig;

https://nextjs.org/docs/pages/building-your-application/deploying/static-exports

amplify init

amplify init を実行します。

$ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project frontend
The following configuration will be applied:

Project information
| Name: frontend
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: react
| Source Directory Path: src
| Distribution Directory Path: build
| Build Command: npm run-script build
| Start Command: npm run-script start

? Initialize the project with the above configuration? No

良い感じに Project Information を察してくれて Initialize the project with the above configuration? と聞かれますが、修正したいので Noにします。

そうすると、ひとつひとつ聞かれるので解凍していきます。

? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
✔ Choose the type of app that you're building · javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path:  .
? Distribution Directory Path: out
? Build Command:  yarn run build
? Start Command: yarn run start
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS access keys
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
? region:  ap-northeast-1
Adding backend environment dev to AWS Amplify app: xxxxxxxx
...

重要なところを掻い摘むと こんな感じで回答していきます。

  • Distribution Directory Pathout
  • Build Commandyarn run build

amplify add hosting

amplify add hosting を実行します。

$ amplify add hosting
? Select the plugin module to execute
  Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
 Amazon CloudFront and S3

Select the plugin module to execute と聞かれるので Amazon CloudFront and S3 を選択します。

amplify publish

あとは amplify publish するだけです。

$ amplify publish    
✔ Successfully pulled backend environment dev from the cloud.

    Current Environment: dev
    
┌──────────┬─────────────────┬───────────┬───────────────────┐
│ Category │ Resource name   │ Operation │ Provider plugin   │
├──────────┼─────────────────┼───────────┼───────────────────┤
│ Hosting  │ S3AndCloudFront │ Create    │ awscloudformation │
└──────────┴─────────────────┴───────────┴───────────────────┘
✔ Are you sure you want to continue? (Y/n) · yes

...
✔ Uploaded files successfully.
Your app is published successfully.
https://xxxxxxxxxxx.cloudfront.net <-- 最後に url が表示されます

これで完了です。とても簡単でした。

Discussion