Skip to content

From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline

Learn to host a Next.js static export on a private S3 bucket with CloudFront, a custom domain, HTTPS, security headers, and automated GitHub to CodePipeline deployments using Terraform.

Author
Navinda Chandrasiri
Published
Reading time
12 min read
Topics
AWSTerraformCloudFrontS3CodePipelineCodeBuildRoute 53Next.jsCI/CDInfrastructure as Code
From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline
On this page

Static sites are wonderfully boring in the best possible way: no servers to patch, no containers to babysit, and a tiny attack surface. If your Next.js app can be exported to plain HTML, CSS, and JavaScript, then the cheapest, fastest, and most secure way to host it on AWS is a private S3 bucket behind CloudFront.

In this post I will walk through the whole setup end to end:

  • A Next.js static export (built into the out directory)
  • A private S3 bucket that nobody can reach except CloudFront
  • CloudFront with HTTPS, HTTP/3, and security headers
  • A custom domain with an ACM certificate and Route 53 DNS
  • A GitHub → CodePipeline → CodeBuild pipeline that deploys on every push
  • All of it provisioned with Terraform, so the entire stack is reproducible and reviewable

By the end, git push will build your site, upload it to S3, and invalidate the CDN cache automatically.

The Architecture#

Here is the big picture:

Architecture diagram: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline.

A few deliberate design decisions worth calling out:

  1. The S3 bucket is never public. CloudFront reaches it through Origin Access Control (OAC), and the bucket policy only trusts this one distribution.
  2. The S3 static website endpoint is not used. That endpoint only speaks HTTP and requires a public bucket. The regular S3 REST endpoint plus OAC is the secure option.
  3. TLS everywhere. HTTP is redirected to HTTPS, and the minimum protocol is TLS 1.2.
  4. Least-privilege IAM. The build role cannot touch the site bucket, and the deploy role can only write to that bucket and invalidate that distribution.
  5. Everything is code. No clicking around the console, apart from one unavoidable GitHub authorization step.

Prerequisites#

  • An AWS account and the AWS CLI configured locally
  • Terraform 1.6 or newer
  • A domain with a public Route 53 hosted zone already created (if the domain is registered elsewhere, point its nameservers at the hosted zone first)
  • A GitHub repository containing your Next.js app

Step 1: Configure Next.js for Static Export#

Open your Next.js config and enable static export:

js
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",      // generates a fully static site in the "out" directory
  trailingSlash: true,   // /about becomes /about/index.html, which maps cleanly to S3 keys
  images: {
    unoptimized: true,   // the default image optimizer needs a server, which we do not have
  },
};
 
export default nextConfig;

Now run npm run build locally. You should see an out folder containing index.html, a 404.html, and a _next/static directory with your hashed JavaScript and CSS bundles.

A few things to keep in mind with static export:

  • Features that need a server (API routes, middleware, ISR, server actions, on-demand revalidation) are not available. Fetch data at build time or from the browser instead.
  • Anything prefixed with NEXT_PUBLIC_ is baked into the bundle and visible to every visitor. Never put secrets in it.

Step 2: Add the Build Spec#

CodeBuild needs to know how to build the site. Create buildspec.yml in the root of your repository:

yaml
# buildspec.yml
version: 0.2
 
phases:
  install:
    runtime-versions:
      nodejs: 20
    commands:
      - npm ci
  build:
    commands:
      - npm run build
 
artifacts:
  base-directory: out
  files:
    - "**/*"

The important line is base-directory: out. It tells CodeBuild to hand only the contents of out to the next pipeline stage, so the deploy step can upload the folder exactly as it is.

Step 3: The Terraform Project#

I keep the infrastructure in an infra/ folder in the same repository:

text
infra/
├── providers.tf
├── variables.tf
├── s3.tf
├── certificate.tf
├── cloudfront.tf
├── dns.tf
├── iam.tf
├── pipeline.tf
└── outputs.tf

Providers#

CloudFront can only use ACM certificates from us-east-1, no matter where the rest of your stack lives. That is why there are two AWS provider configurations:

hcl
# infra/providers.tf
terraform {
  required_version = ">= 1.6"
 
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
 
provider "aws" {
  region = var.aws_region
}
 
# Alias used only for the CloudFront certificate
provider "aws" {
  alias  = "us_east_1"
  region = "us-east-1"
}
 
data "aws_caller_identity" "current" {}
 
locals {
  account_id    = data.aws_caller_identity.current.account_id
  log_group_arn = "arn:aws:logs:${var.aws_region}:${local.account_id}:log-group:/aws/codebuild/${var.project}-*"
}

Variables#

hcl
# infra/variables.tf
variable "aws_region" {
  type    = string
  default = "ap-southeast-1"
}
 
variable "project" {
  type        = string
  description = "Short name used to prefix resources"
  default     = "nextjs-static-site"
}
 
variable "hosted_zone_name" {
  type        = string
  description = "Existing public Route 53 hosted zone, for example example.com"
}
 
variable "site_domain" {
  type        = string
  description = "Domain the site is served from, for example www.example.com"
}
 
variable "github_repo" {
  type        = string
  description = "GitHub repository in owner/repo format"
}
 
variable "github_branch" {
  type    = string
  default = "main"
}

And a terraform.tfvars with your real values:

hcl
# infra/terraform.tfvars
hosted_zone_name = "example.com"
site_domain      = "www.example.com"
github_repo      = "your-github-username/your-repo"

The Private S3 Bucket#

This is the heart of the security story. Public access is blocked at every level, objects are encrypted, versioning gives us rollbacks, and the bucket policy trusts exactly one CloudFront distribution:

hcl
# infra/s3.tf
resource "aws_s3_bucket" "site" {
  bucket = "${var.project}-site-${local.account_id}"
}
 
resource "aws_s3_bucket_ownership_controls" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}
 
resource "aws_s3_bucket_public_access_block" "site" {
  bucket                  = aws_s3_bucket.site.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
 
resource "aws_s3_bucket_server_side_encryption_configuration" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}
 
resource "aws_s3_bucket_versioning" "site" {
  bucket = aws_s3_bucket.site.id
 
  versioning_configuration {
    status = "Enabled"
  }
}
 
# Old versions are only useful for a short rollback window
resource "aws_s3_bucket_lifecycle_configuration" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    id     = "expire-old-versions"
    status = "Enabled"
 
    filter {}
 
    noncurrent_version_expiration {
      noncurrent_days = 30
    }
  }
 
  depends_on = [aws_s3_bucket_versioning.site]
}
 
data "aws_iam_policy_document" "site_bucket" {
  # Only this CloudFront distribution may read objects
  statement {
    sid       = "AllowCloudFrontRead"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.site.arn}/*"]
 
    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }
 
    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.site.arn]
    }
  }
 
  # Refuse any request that is not over TLS
  statement {
    sid       = "DenyInsecureTransport"
    effect    = "Deny"
    actions   = ["s3:*"]
    resources = [aws_s3_bucket.site.arn, "${aws_s3_bucket.site.arn}/*"]
 
    principals {
      type        = "*"
      identifiers = ["*"]
    }
 
    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}
 
resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
  policy = data.aws_iam_policy_document.site_bucket.json
 
  depends_on = [aws_s3_bucket_public_access_block.site]
}

The HTTPS Certificate#

ACM validates ownership by DNS. Because the hosted zone lives in Route 53, Terraform can create the validation records and wait for the certificate to be issued, all in one run:

hcl
# infra/certificate.tf
data "aws_route53_zone" "main" {
  name         = var.hosted_zone_name
  private_zone = false
}
 
resource "aws_acm_certificate" "site" {
  provider          = aws.us_east_1
  domain_name       = var.site_domain
  validation_method = "DNS"
 
  lifecycle {
    create_before_destroy = true
  }
}
 
resource "aws_route53_record" "cert_validation" {
  for_each = {
    for dvo in aws_acm_certificate.site.domain_validation_options : dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    }
  }
 
  allow_overwrite = true
  zone_id         = data.aws_route53_zone.main.zone_id
  name            = each.value.name
  type            = each.value.type
  ttl             = 60
  records         = [each.value.record]
}
 
resource "aws_acm_certificate_validation" "site" {
  provider                = aws.us_east_1
  certificate_arn         = aws_acm_certificate.site.arn
  validation_record_fqdns = [for record in aws_route53_record.cert_validation : record.fqdn]
}

CloudFront: Origin Access Control, URL Rewrites, and Security Headers#

There are three pieces here besides the distribution itself.

Origin Access Control (OAC) lets CloudFront sign its requests to S3 with SigV4. It is the modern replacement for the old Origin Access Identity.

A CloudFront Function fixes a classic static-hosting gotcha. S3's REST endpoint does not automatically serve index.html for a folder-style URL like /blog/, so the function rewrites those requests before they hit the origin.

A response headers policy adds browser-side protections to every response.

hcl
# infra/cloudfront.tf
resource "aws_cloudfront_origin_access_control" "site" {
  name                              = "${var.project}-oac"
  description                       = "OAC for the static site bucket"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}
 
resource "aws_cloudfront_function" "index_rewrite" {
  name    = "${var.project}-index-rewrite"
  runtime = "cloudfront-js-2.0"
  publish = true
 
  code = <<-EOF
    function handler(event) {
      var request = event.request;
      var uri = request.uri;
 
      if (uri.endsWith('/')) {
        request.uri = uri + 'index.html';
      } else if (!uri.includes('.')) {
        request.uri = uri + '/index.html';
      }
 
      return request;
    }
  EOF
}
 
resource "aws_cloudfront_response_headers_policy" "security" {
  name = "${var.project}-security-headers"
 
  security_headers_config {
    strict_transport_security {
      access_control_max_age_sec = 63072000
      include_subdomains         = true
      preload                    = false
      override                   = true
    }
 
    content_type_options {
      override = true
    }
 
    frame_options {
      frame_option = "DENY"
      override     = true
    }
 
    referrer_policy {
      referrer_policy = "strict-origin-when-cross-origin"
      override        = true
    }
 
    content_security_policy {
      content_security_policy = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
      override                = true
    }
  }
 
  custom_headers_config {
    items {
      header   = "Permissions-Policy"
      value    = "camera=(), microphone=(), geolocation=()"
      override = true
    }
  }
}
 
# AWS managed cache policy: gzip/brotli, sensible TTLs
data "aws_cloudfront_cache_policy" "optimized" {
  name = "Managed-CachingOptimized"
}
 
resource "aws_cloudfront_distribution" "site" {
  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2and3"
  comment             = "${var.project} static site"
  default_root_object = "index.html"
  aliases             = [var.site_domain]
  price_class         = "PriceClass_100"
 
  origin {
    domain_name              = aws_s3_bucket.site.bucket_regional_domain_name
    origin_id                = "s3-site"
    origin_access_control_id = aws_cloudfront_origin_access_control.site.id
  }
 
  default_cache_behavior {
    target_origin_id           = "s3-site"
    viewer_protocol_policy     = "redirect-to-https"
    allowed_methods            = ["GET", "HEAD", "OPTIONS"]
    cached_methods             = ["GET", "HEAD"]
    compress                   = true
    cache_policy_id            = data.aws_cloudfront_cache_policy.optimized.id
    response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id
 
    function_association {
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.index_rewrite.arn
    }
  }
 
  # With OAC and no s3:ListBucket permission, S3 answers 403 for missing keys.
  # Map both 403 and 404 to the Next.js 404 page.
  custom_error_response {
    error_code            = 403
    response_code         = 404
    response_page_path    = "/404.html"
    error_caching_min_ttl = 60
  }
 
  custom_error_response {
    error_code            = 404
    response_code         = 404
    response_page_path    = "/404.html"
    error_caching_min_ttl = 60
  }
 
  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }
 
  viewer_certificate {
    acm_certificate_arn      = aws_acm_certificate_validation.site.certificate_arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = "TLSv1.2_2021"
  }
}

A note on the Content Security Policy: Next.js injects small inline scripts into every exported page, so a strict script-src without 'unsafe-inline' will break hydration unless you add hashes or nonces. The policy above is a sensible starting point. Tighten it once you know exactly which third-party scripts, fonts, and APIs your site uses.

Route 53 Records#

Alias records point your domain at CloudFront, for both IPv4 (A) and IPv6 (AAAA):

hcl
# infra/dns.tf
resource "aws_route53_record" "site_a" {
  zone_id = data.aws_route53_zone.main.zone_id
  name    = var.site_domain
  type    = "A"
 
  alias {
    name                   = aws_cloudfront_distribution.site.domain_name
    zone_id                = aws_cloudfront_distribution.site.hosted_zone_id
    evaluate_target_health = false
  }
}
 
resource "aws_route53_record" "site_aaaa" {
  zone_id = data.aws_route53_zone.main.zone_id
  name    = var.site_domain
  type    = "AAAA"
 
  alias {
    name                   = aws_cloudfront_distribution.site.domain_name
    zone_id                = aws_cloudfront_distribution.site.hosted_zone_id
    evaluate_target_health = false
  }
}

IAM: Least Privilege for the Pipeline#

This is where many tutorials get lazy and attach AdministratorAccess to everything. We will not. There are three roles, each with only what it needs:

  • CodePipeline role: orchestrates the stages and uses the GitHub connection
  • Build role: reads the source and writes the build output to the artifact bucket, nothing else
  • Deploy role: writes to the site bucket and creates invalidations for this one distribution
hcl
# infra/iam.tf
data "aws_iam_policy_document" "codebuild_assume" {
  statement {
    actions = ["sts:AssumeRole"]
 
    principals {
      type        = "Service"
      identifiers = ["codebuild.amazonaws.com"]
    }
  }
}
 
data "aws_iam_policy_document" "codepipeline_assume" {
  statement {
    actions = ["sts:AssumeRole"]
 
    principals {
      type        = "Service"
      identifiers = ["codepipeline.amazonaws.com"]
    }
  }
}
 
# ---------- Build role ----------
resource "aws_iam_role" "build" {
  name               = "${var.project}-codebuild-build"
  assume_role_policy = data.aws_iam_policy_document.codebuild_assume.json
}
 
data "aws_iam_policy_document" "build" {
  statement {
    actions   = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"]
    resources = [local.log_group_arn, "${local.log_group_arn}:*"]
  }
 
  statement {
    actions   = ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject"]
    resources = ["${aws_s3_bucket.artifacts.arn}/*"]
  }
}
 
resource "aws_iam_role_policy" "build" {
  role   = aws_iam_role.build.id
  policy = data.aws_iam_policy_document.build.json
}
 
# ---------- Deploy role ----------
resource "aws_iam_role" "deploy" {
  name               = "${var.project}-codebuild-deploy"
  assume_role_policy = data.aws_iam_policy_document.codebuild_assume.json
}
 
data "aws_iam_policy_document" "deploy" {
  statement {
    actions   = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"]
    resources = [local.log_group_arn, "${local.log_group_arn}:*"]
  }
 
  statement {
    actions   = ["s3:GetObject", "s3:GetObjectVersion"]
    resources = ["${aws_s3_bucket.artifacts.arn}/*"]
  }
 
  statement {
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.site.arn]
  }
 
  statement {
    actions   = ["s3:PutObject", "s3:DeleteObject"]
    resources = ["${aws_s3_bucket.site.arn}/*"]
  }
 
  statement {
    actions   = ["cloudfront:CreateInvalidation"]
    resources = [aws_cloudfront_distribution.site.arn]
  }
}
 
resource "aws_iam_role_policy" "deploy" {
  role   = aws_iam_role.deploy.id
  policy = data.aws_iam_policy_document.deploy.json
}
 
# ---------- CodePipeline role ----------
resource "aws_iam_role" "pipeline" {
  name               = "${var.project}-codepipeline"
  assume_role_policy = data.aws_iam_policy_document.codepipeline_assume.json
}
 
data "aws_iam_policy_document" "pipeline" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:GetObjectVersion",
      "s3:GetBucketVersioning",
      "s3:PutObject",
    ]
    resources = [aws_s3_bucket.artifacts.arn, "${aws_s3_bucket.artifacts.arn}/*"]
  }
 
  statement {
    actions   = ["codestar-connections:UseConnection", "codeconnections:UseConnection"]
    resources = [aws_codestarconnections_connection.github.arn]
  }
 
  statement {
    actions = ["codebuild:BatchGetBuilds", "codebuild:StartBuild"]
    resources = [
      aws_codebuild_project.build.arn,
      aws_codebuild_project.deploy.arn,
    ]
  }
}
 
resource "aws_iam_role_policy" "pipeline" {
  role   = aws_iam_role.pipeline.id
  policy = data.aws_iam_policy_document.pipeline.json
}

The Pipeline#

Now the fun part. There are three stages:

  1. Source: watches the GitHub branch through an AWS CodeConnections (formerly CodeStar) connection
  2. Build: runs npm ci and next build, then passes the out folder along
  3. Deploy: syncs the files to S3 with smart cache headers, then invalidates CloudFront

The deploy stage deserves a closer look at its caching strategy. Next.js puts a content hash in the file name of everything under _next/static, so those files can be cached for a year with the immutable directive. HTML pages, on the other hand, must always be revalidated so visitors see new content right after a deployment.

hcl
# infra/pipeline.tf
resource "aws_codestarconnections_connection" "github" {
  name          = "${var.project}-github"
  provider_type = "GitHub"
}
 
resource "aws_s3_bucket" "artifacts" {
  bucket        = "${var.project}-pipeline-artifacts-${local.account_id}"
  force_destroy = true
}
 
resource "aws_s3_bucket_public_access_block" "artifacts" {
  bucket                  = aws_s3_bucket.artifacts.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
 
resource "aws_s3_bucket_server_side_encryption_configuration" "artifacts" {
  bucket = aws_s3_bucket.artifacts.id
 
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}
 
# ---------- Build project: npm ci && next build ----------
resource "aws_codebuild_project" "build" {
  name          = "${var.project}-build"
  service_role  = aws_iam_role.build.arn
  build_timeout = 15
 
  artifacts {
    type = "CODEPIPELINE"
  }
 
  environment {
    compute_type = "BUILD_GENERAL1_SMALL"
    image        = "aws/codebuild/standard:7.0"
    type         = "LINUX_CONTAINER"
  }
 
  source {
    type      = "CODEPIPELINE"
    buildspec = "buildspec.yml"
  }
}
 
# ---------- Deploy project: sync to S3 and invalidate the CDN ----------
resource "aws_codebuild_project" "deploy" {
  name          = "${var.project}-deploy"
  service_role  = aws_iam_role.deploy.arn
  build_timeout = 10
 
  artifacts {
    type = "CODEPIPELINE"
  }
 
  environment {
    compute_type = "BUILD_GENERAL1_SMALL"
    image        = "aws/codebuild/standard:7.0"
    type         = "LINUX_CONTAINER"
 
    environment_variable {
      name  = "SITE_BUCKET"
      value = aws_s3_bucket.site.id
    }
 
    environment_variable {
      name  = "DISTRIBUTION_ID"
      value = aws_cloudfront_distribution.site.id
    }
  }
 
  source {
    type      = "CODEPIPELINE"
    buildspec = <<-EOT
      version: 0.2
      phases:
        build:
          commands:
            - echo "Uploading hashed assets with one-year immutable caching"
            - aws s3 sync . s3://$SITE_BUCKET --exclude "*" --include "_next/static/*" --cache-control "public,max-age=31536000,immutable"
            - echo "Uploading everything else and removing deleted files"
            - aws s3 sync . s3://$SITE_BUCKET --delete --exclude "_next/static/*" --cache-control "public,max-age=0,must-revalidate"
            - echo "Invalidating the CloudFront cache"
            - aws cloudfront create-invalidation --distribution-id $DISTRIBUTION_ID --paths "/*"
    EOT
  }
}
 
# ---------- The pipeline ----------
resource "aws_codepipeline" "site" {
  name          = "${var.project}-pipeline"
  role_arn      = aws_iam_role.pipeline.arn
  pipeline_type = "V2"
 
  artifact_store {
    location = aws_s3_bucket.artifacts.bucket
    type     = "S3"
  }
 
  stage {
    name = "Source"
 
    action {
      name             = "GitHub"
      category         = "Source"
      owner            = "AWS"
      provider         = "CodeStarSourceConnection"
      version          = "1"
      output_artifacts = ["source_output"]
 
      configuration = {
        ConnectionArn        = aws_codestarconnections_connection.github.arn
        FullRepositoryId     = var.github_repo
        BranchName           = var.github_branch
        OutputArtifactFormat = "CODE_ZIP"
        DetectChanges        = "true"
      }
    }
  }
 
  stage {
    name = "Build"
 
    action {
      name             = "BuildNextJs"
      category         = "Build"
      owner            = "AWS"
      provider         = "CodeBuild"
      version          = "1"
      input_artifacts  = ["source_output"]
      output_artifacts = ["build_output"]
 
      configuration = {
        ProjectName = aws_codebuild_project.build.name
      }
    }
  }
 
  stage {
    name = "Deploy"
 
    action {
      name            = "SyncToS3AndInvalidate"
      category        = "Build"
      owner           = "AWS"
      provider        = "CodeBuild"
      version         = "1"
      input_artifacts = ["build_output"]
 
      configuration = {
        ProjectName = aws_codebuild_project.deploy.name
      }
    }
  }
}

Outputs#

hcl
# infra/outputs.tf
output "site_url" {
  value = "https://${var.site_domain}"
}
 
output "cloudfront_domain" {
  value = aws_cloudfront_distribution.site.domain_name
}
 
output "cloudfront_distribution_id" {
  value = aws_cloudfront_distribution.site.id
}
 
output "github_connection_arn" {
  value = aws_codestarconnections_connection.github.arn
}

Step 4: Deploy the Infrastructure#

From the infra/ directory:

bash
terraform init
terraform plan
terraform apply

The first apply takes a few minutes. CloudFront distributions are slow to create, and Terraform also waits for ACM to validate the certificate through DNS.

The one manual step: authorize GitHub#

A new CodeConnections connection is created in a Pending state, and only a human can approve it, because it needs you to log in to GitHub and grant access. In the AWS console, go to Developer Tools → Settings → Connections, open the connection Terraform created, and choose Update pending connection. Follow the GitHub prompts and install the AWS connector app on your repository.

Once it shows Available, open your pipeline and click Release change, or simply push a commit.

Step 5: Ship It#

Commit the buildspec.yml and your Next.js changes, then push:

bash
git add .
git commit -m "Add static export config and build spec"
git push origin main

Open CodePipeline in the console and watch the stages turn green: Source, Build, Deploy. When it finishes, visit your domain. You should see your site over HTTPS, served from the nearest CloudFront edge location.

Want to double-check that the security headers are really being sent?

bash
curl -sI https://www.example.com | grep -iE "strict-transport|content-security|x-frame|x-content-type|referrer|permissions"

And to confirm the bucket really is private, try fetching an object straight from S3. You should get an AccessDenied response:

bash
curl -I https://YOUR-BUCKET-NAME.s3.amazonaws.com/index.html

The Security Checklist#

Here is what this setup gives you, summarized:

  • Private origin: all four S3 Block Public Access settings are on, and only the CloudFront distribution can read objects (OAC with SigV4)
  • Encryption in transit: HTTP redirects to HTTPS, TLS 1.2 or newer is enforced, and the bucket denies any non-TLS request
  • Encryption at rest: server-side encryption on both buckets
  • Browser hardening: HSTS, CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy on every response
  • Least-privilege IAM: separate roles for orchestration, build, and deploy, each scoped to specific resources
  • No long-lived credentials: CodeBuild uses role-based temporary credentials, and no AWS keys live in GitHub
  • Auditable infrastructure: every change goes through Terraform, so it can be reviewed in a pull request
  • Rollback path: S3 versioning plus git history means you can always get back to a known-good state

Gotchas I Ran Into (So You Do Not Have To)#

Refreshing a nested page returns an error. S3 does not know that /blog/ means /blog/index.html. The CloudFront Function above fixes this, and trailingSlash: true in Next.js makes the exported file layout match the URLs.

Missing pages show an XML error instead of your 404 page. Without s3:ListBucket permission for CloudFront, S3 returns 403 (not 404) for missing keys. That is why the distribution maps both 403 and 404 to /404.html.

The certificate will not attach to the distribution. It must live in us-east-1. This is the reason for the provider alias.

Old content is still showing after a deploy. Check that the invalidation ran in the deploy stage logs. Also keep HTML at max-age=0 so browsers revalidate rather than holding on to stale pages.

The CSP is blocking my scripts or fonts. Open the browser console, since violations are reported there with the exact directive involved. Add only the specific origins you need.

Pipeline fails on the very first run. That is almost always the GitHub connection still being in the Pending state. Authorize it and release the change again.

Where to Go Next#

  • Remote Terraform state. Store state in a versioned S3 bucket with locking, so your whole team (and your future self) can run Terraform safely.
  • Add a www to apex redirect (or the reverse) with a second alias on the distribution plus a CloudFront Function redirect.
  • Turn on CloudFront standard logging or AWS WAF if the site handles anything sensitive or attracts abusive traffic.
  • Add pipeline notifications through Amazon SNS or AWS Chatbot so a failed deployment pings you in Slack or email.
  • Expire old pipeline artifacts with an S3 lifecycle rule on the artifact bucket.
  • Add a manual approval stage between Build and Deploy if you want a human gate for production.

Wrapping Up#

With roughly a dozen small Terraform files and a ten-line build spec, you now have a production-grade static hosting platform: private storage, a global CDN, HTTPS on your own domain, hardened headers, and a pipeline that turns git push into a live deployment in a couple of minutes. There are no servers to maintain, the running costs are typically very small for a static site (check the AWS pricing pages for your region and traffic), and everything can be torn down or recreated with a single command.

If you want to tear the whole thing down when you are done experimenting, empty the site bucket first, then run terraform destroy.

Happy shipping! If this guide helped you, or if you hit a snag I did not cover, I would love to hear about it.

Portrait of Navinda Chandrasiri

Written by Navinda Chandrasiri

Senior Software Engineer in Colombo, Sri Lanka, building cloud-native web applications and AI systems.

See my portfolio

ShareLinkedInX

  1. Zero Servers, One Bucket: Deploying a Next.js Static Site to Amazon S3 with Terraform and CodePipeline

    Host a Next.js static export on Amazon S3 website hosting and automate every deployment from GitHub using AWS CodePipeline, CodeBuild, and Terraform, with the trade-offs explained honestly.

    AWSTerraformS3CodePipeline

    12 min read
  2. Before the First Server: Designing a Production Ready AWS VPC from Scratch with Terraform

    Build a production ready AWS VPC with Terraform, covering multi-AZ subnets, route tables, NAT and internet gateways, security groups, NACLs, VPC endpoints, and flow logs.

    AWSVPCTerraformNetworking

    20 min read
  3. From Commit to Two Regions: A Multi-Region CI/CD Pipeline with AWS CodePipeline and CodeDeploy

    Build a CI/CD pipeline on AWS DevOps tools: GitHub triggers CodePipeline, CodeDeploy ships to EC2 in two Regions, with a manual approval gate and an automated Lambda readiness check.

    AWSCI/CDCodePipelineCodeDeploy

    14 min read