AWS - Deploy Next.js Application to AWS S3

Create an S3 Bucket

  • Go to Services > S3

  • Click on Create bucket

  • Enter a unique name for the bucket (e.g. my-next-app)

  • Uncheck Block all public access

  • Check the acknowledgment

  • Click on Create bucket

Enable static website hosting

  • Click on the created bucket

  • Go to Properties > Static website hosting

  • Select Use this bucket to host a website

  • Enter index.html for Index document and Error document

  • Click Save

Enable public access to the bucket using a bucket policy.

  • Go to Permissions > Bucket Policy

  • Enter the following policy and click Save

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<YOUR_S3_BUCKET_NAME>/*"
        }
    ]
}

Replace <YOUR_S3_BUCKET_NAME> with your bucket name at Resource.

Static HTML Export

  • Add next export to package.json

  • Run yarn build

  • Run yarn export

  "scripts": {
    "build": "next build && next export",
    "export": "next export",
  },

Publish Next.js Application to S3 bucket

aws s3 sync out s3://<YOUR_S3_BUCKET_NAME> --delete

Invalidating files from CloudFront edge caches before it expires

aws cloudfront create-invalidation --distribution-id <YOUR_CLOUDFRONT_DISTRIBUTION_ID> --paths '/*'

Replace <YOUR_S3_BUCKET_NAME> with your bucket name. Replace <YOUR_CLOUDFRONT_DISTRIBUTION_ID> with your distribution id.

Last updated

Was this helpful?