SSGって何だっけ?
SSG(Static Site Generation)は、リクエストごとではなくビルド時にHTMLを生成する仕組みです。
これにより、ページの読み込みが速く、サーバーコストもゼロ!
もし「サーバーを立てずに、低コストでWebサイトを公開したい!」という方には、S3のような静的ホスティングがまさにピッタリです(安いし)。
ステップ1:next.config.js
を更新する
Next.jsに「静的サイトとして出力してね」と教えます。
// next.config.js
const nextConfig = {
output: 'export',
}
module.exports = nextConfig
ステップ2:GHA用のIAMロールを作成する
S3にデプロイするためには、GitHub ActionsがS3へアクセスできるようにIAMロールとポリシーを作成する必要があります。
以下はCloudFormationでIAMロールにS3アクセス権限を付与する例です。(バケット名やロール名はマスクしています)
IAMロール(GitHub Actions OIDC用)
IAMRoleExampleForGHA:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${ServiceName}-gha
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: sts:AssumeRoleWithWebIdentity
Principal:
Federated: !ImportValue your-platform-base::GithubOidcArn
Condition:
StringEquals:
token.actions.githubusercontent.com:aud:
- sts.amazonaws.com
ForAnyValue:StringLike:
token.actions.githubusercontent.com:sub:
- !Sub 'repo:${YourRepositoryName}:ref:refs/heads/main'
- !Sub 'repo:${YourRepositoryName}:pull_request'
- !Sub 'repo:${YourRepositoryName}:push'
IAMポリシー(S3アクセス権限付与用)
IAMPolicyAccessToS3Example:
Type: "AWS::IAM::Policy"
Properties:
PolicyName: "IAMPolicyAccessToS3Example"
Roles:
- !Ref IAMRoleExampleForGHA
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: "AccessToS3Example"
Effect: "Allow"
Action:
- "s3:DeleteObject"
- "s3:GetObject"
- "s3:GetObjectAcl"
- "s3:PutObject"
- "s3:PutObjectAcl"
- "s3:ListBucket"
Resource:
- !Sub "${S3BucketExample.Arn}"
- !Sub "${S3BucketExample.Arn}/*"
ポイント:
- Resource には対象のS3バケットARNを指定
- Roles にはGitHub ActionsからAssume RoleするIAMロール名を指定
- CloudFormationを使わずマネコンから作ってもOKですが、Infrastructure as Codeで管理するのがおすすめ
ステップ3:GitHub Actionsで自動デプロイ
GitHub Actionsを使って、Next.jsアプリをビルド → S3にアップロードする流れを自動化します。
on:
push:
branches: ['main']
permissions:
actions: write
contents: read
id-token: write
jobs:
upload:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::<your-account-id>:role/<your-gha-role>
aws-region: ap-northeast-1
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install Dependencies
run: npm ci
- name: Build
run: npm run build
- name: Deploy to s3
run: |
aws s3 cp --recursive ./out/ s3://your-static-site-bucket-name --acl public-read
注意ポイント
-
getServerSideProps()
は使わず、getStaticProps()
または通常のページを使う - 動的ルートは事前ビルドされていないと動かない
- S3はクライアントサイドルーティングを扱えないため、ルーティングが壊れた場合はCloudFront + fallback設定が必要になることも
これで、プッシュするだけでS3に静的サイトがデプロイされます!🚀
「毎回手動でアップロード…」から卒業して、楽しましょう。