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.
- Author
- Navinda Chandrasiri
- Published
- Reading time
- 12 min read

On this page
- When Does This Setup Make Sense?
- The Architecture
- Prerequisites
- Step 1: Configure Next.js for Static Export
- Step 2: Add the Build Spec
- Step 3: Write the Terraform
- Providers and Variables
- The Website Bucket
- The Pipeline Artifact Bucket
- IAM: Only What Each Role Needs
- The Build Project and the Pipeline
- Outputs
- Step 4: Apply the Infrastructure
- The one manual step: authorize GitHub
- Step 5: Push and Watch It Deploy
- Security Notes: Know What You Are Exposing
- Gotchas Worth Knowing
- Where to Go Next
- Cleaning Up
- Wrapping Up
Sometimes you do not need a global CDN, a custom domain, or a dozen moving parts. Sometimes you just need your Next.js site live on the internet, deployed automatically, with as little infrastructure as possible.
That is exactly what a single S3 bucket can give you. In this post I will show you how to:
- Export a Next.js app as a static site into the
outdirectory - Host it on Amazon S3 static website hosting
- Build and deploy it automatically with GitHub → AWS CodePipeline → CodeBuild → S3
- Provision everything with Terraform, so the setup is repeatable and lives in version control
I will also be upfront about what this setup does not give you (hello, HTTPS), and point you at the upgrade path when you need it.
When Does This Setup Make Sense?#
S3 website hosting is a great fit for:
- Demos, prototypes, and learning projects
- Internal tools and team previews
- Staging or preview environments
- Documentation and small personal sites where plain HTTP is acceptable
It is not the right final answer for a public production site, because the S3 website endpoint only supports HTTP and requires a publicly readable bucket. If you need HTTPS, a custom domain, or security headers, put CloudFront in front of a private bucket instead. I cover that setup in my other post, Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline, and the pipeline you build here carries over to it almost unchanged.
The Architecture#
Only four AWS resources do the real work: an S3 bucket for the website, an S3 bucket for pipeline artifacts, a CodeBuild project, and the pipeline itself. Plus some IAM glue.
Prerequisites#
- An AWS account and the AWS CLI configured locally
- Terraform 1.6 or newer
- A GitHub repository with your Next.js app
- Permission to make a bucket public (more on this in the gotchas section)
Step 1: Configure Next.js for Static Export#
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export", // build a fully static site into the "out" directory
trailingSlash: true, // /about becomes /about/index.html, which S3 website hosting understands
images: {
unoptimized: true, // the default image optimizer needs a server
},
};
export default nextConfig;Run npm run build and look inside out. You should find index.html, 404.html, and a _next folder with your bundles. If you want to preview the result locally before involving AWS:
npx serve outTwo reminders about static export:
- Server-only features (API routes, middleware, server actions, ISR) are unavailable. Fetch data at build time or in the browser.
- Variables starting with
NEXT_PUBLIC_are embedded in the bundle. Never store secrets in them. With this setup, everything in the bucket is public.
The trailingSlash: true setting matters here. S3 website hosting serves the index document for folder-style paths like /about/, so exporting each page as about/index.html makes your URLs work naturally.
Step 2: Add the Build Spec#
CodeBuild reads its instructions from buildspec.yml in the root of your repository:
# 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 key line is base-directory: out. The pipeline's next stage receives the contents of out at the root of the artifact, which is exactly what we want to land in the bucket.
Step 3: Write the Terraform#
I keep the infrastructure alongside the app in an infra/ folder:
infra/
├── providers.tf
├── variables.tf
├── s3.tf
├── iam.tf
├── pipeline.tf
└── outputs.tfProviders and Variables#
# infra/providers.tf
terraform {
required_version = ">= 1.6"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
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}-*"
}# 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-s3-site"
}
variable "github_repo" {
type = string
description = "GitHub repository in owner/repo format"
}
variable "github_branch" {
type = string
default = "main"
}Create a terraform.tfvars with your own repository:
# infra/terraform.tfvars
github_repo = "your-github-username/your-repo"The Website Bucket#
S3 bucket names are globally unique, so I add the AWS account ID as a suffix. The interesting part is the public access block: we deliberately allow a public bucket policy, but we still keep ACLs locked down so nothing can be made public by accident through an object ACL.
# infra/s3.tf
resource "aws_s3_bucket" "site" {
bucket = "${var.project}-site-${local.account_id}"
}
# ACLs are disabled entirely. Access is controlled only by the bucket policy.
resource "aws_s3_bucket_ownership_controls" "site" {
bucket = aws_s3_bucket.site.id
rule {
object_ownership = "BucketOwnerEnforced"
}
}
# Block ACL-based public access, but allow a public bucket policy
resource "aws_s3_bucket_public_access_block" "site" {
bucket = aws_s3_bucket.site.id
block_public_acls = true
ignore_public_acls = true
block_public_policy = false
restrict_public_buckets = false
}
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_website_configuration" "site" {
bucket = aws_s3_bucket.site.id
index_document {
suffix = "index.html"
}
error_document {
key = "404.html"
}
}
# Anyone may read objects. Nobody can list, write, or delete through this policy.
data "aws_iam_policy_document" "site_public_read" {
statement {
sid = "PublicReadGetObject"
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.site.arn}/*"]
principals {
type = "*"
identifiers = ["*"]
}
}
}
resource "aws_s3_bucket_policy" "site" {
bucket = aws_s3_bucket.site.id
policy = data.aws_iam_policy_document.site_public_read.json
depends_on = [aws_s3_bucket_public_access_block.site]
}The Pipeline Artifact Bucket#
CodePipeline needs somewhere to pass files between stages. This bucket is the opposite of the website bucket: completely private, encrypted, and with old artifacts expiring automatically.
# infra/s3.tf (continued)
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"
}
}
}
resource "aws_s3_bucket_lifecycle_configuration" "artifacts" {
bucket = aws_s3_bucket.artifacts.id
rule {
id = "expire-old-artifacts"
status = "Enabled"
filter {}
expiration {
days = 14
}
}
}IAM: Only What Each Role Needs#
Two roles are required:
- CodeBuild role: write logs, read the source artifact, write the build output
- CodePipeline role: use the GitHub connection, start builds, move artifacts, and write to the website bucket
Notice that CodeBuild never gets access to the website bucket. In this design, only the pipeline's deploy action publishes the site.
# 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"]
}
}
}
# ---------- CodeBuild role ----------
resource "aws_iam_role" "build" {
name = "${var.project}-codebuild"
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
}
# ---------- 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" {
# Artifact store
statement {
actions = [
"s3:GetObject",
"s3:GetObjectVersion",
"s3:GetBucketVersioning",
"s3:PutObject",
]
resources = [aws_s3_bucket.artifacts.arn, "${aws_s3_bucket.artifacts.arn}/*"]
}
# Deploy action: publish the site
statement {
actions = [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutObjectVersionAcl",
]
resources = ["${aws_s3_bucket.site.arn}/*"]
}
# Source action: GitHub connection
statement {
actions = ["codestar-connections:UseConnection", "codeconnections:UseConnection"]
resources = [aws_codestarconnections_connection.github.arn]
}
# Build action
statement {
actions = ["codebuild:BatchGetBuilds", "codebuild:StartBuild"]
resources = [aws_codebuild_project.build.arn]
}
}
resource "aws_iam_role_policy" "pipeline" {
role = aws_iam_role.pipeline.id
policy = data.aws_iam_policy_document.pipeline.json
}The Build Project and the Pipeline#
This time the deploy stage uses CodePipeline's built-in S3 deploy action, so we do not need a second CodeBuild project. With Extract set to true, the pipeline unzips the build artifact straight into the website bucket.
# infra/pipeline.tf
resource "aws_codestarconnections_connection" "github" {
name = "${var.project}-github"
provider_type = "GitHub"
}
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"
}
}
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 = "DeployToS3"
category = "Deploy"
owner = "AWS"
provider = "S3"
version = "1"
input_artifacts = ["build_output"]
configuration = {
BucketName = aws_s3_bucket.site.bucket
Extract = "true"
CacheControl = "max-age=0, must-revalidate"
}
}
}
}About that CacheControl setting: the S3 deploy action applies one value to every object it uploads. Using max-age=0, must-revalidate means browsers check with S3 on every visit, but because S3 supports ETags, an unchanged file costs only a tiny 304 response. The result is that visitors see a new deployment immediately, with no CDN cache to invalidate.
Outputs#
# infra/outputs.tf
output "website_url" {
description = "Public URL of the site (HTTP only)"
value = "http://${aws_s3_bucket_website_configuration.site.website_endpoint}"
}
output "site_bucket" {
value = aws_s3_bucket.site.bucket
}
output "github_connection_arn" {
value = aws_codestarconnections_connection.github.arn
}Step 4: Apply the Infrastructure#
cd infra
terraform init
terraform plan
terraform applyThe apply finishes in under a minute, because there is no CloudFront distribution or certificate to wait for.
The one manual step: authorize GitHub#
New CodeConnections connections start in a Pending state, and only you can approve them. 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 the status says Available, open the pipeline and click Release change.
Step 5: Push and Watch It Deploy#
Commit the Next.js config and buildspec.yml, then push:
git add .
git commit -m "Configure static export and build spec"
git push origin mainOpen CodePipeline and watch Source, Build, and Deploy turn green. Then grab the URL Terraform printed:
terraform output website_urlOpen it in your browser, and your Next.js site is live. From now on, every push to main redeploys automatically.
You can also verify the behavior from the command line:
# The home page should return 200
curl -I "$(terraform output -raw website_url)"
# A missing page should return your custom 404 page content
curl -i "$(terraform output -raw website_url)/does-not-exist/"Security Notes: Know What You Are Exposing#
A public website bucket has a different security posture from the private-bucket-plus-CDN pattern, so here is the honest summary.
What this setup does well:
- Read-only public access. The bucket policy grants only
s3:GetObject. Visitors cannot list, upload, or delete anything. - ACLs are disabled.
BucketOwnerEnforcedplus the ACL blocks mean no stray object can be made public through an ACL. - Encrypted at rest with S3-managed keys.
- Separate private artifact bucket for the pipeline.
- No AWS keys in GitHub. CodePipeline and CodeBuild use IAM roles with temporary credentials.
- Scoped IAM roles. The build role cannot touch the website bucket at all.
What you accept with this setup:
- HTTP only. The S3 website endpoint does not support HTTPS, so traffic is unencrypted in transit. Do not put anything sensitive on a site like this, and do not collect passwords or personal data through it.
- Everything in the bucket is public. Do not drop private files, source maps you would rather keep to yourself, or secrets into
out. - No security headers. There is no HSTS, CSP, or similar protection, because there is nothing between S3 and the visitor to add them.
- No custom domain over HTTPS and no edge caching, so every visitor connects to the bucket's region.
Gotchas Worth Knowing#
Terraform fails with an AccessDenied error on the bucket policy. Your account (or organization) probably has account-level Block Public Access enabled, which overrides the bucket-level settings. Either disable it for the account if that is acceptable in your environment, or skip this approach and use the CloudFront pattern instead, which keeps the bucket private.
Deleted pages stay online. The S3 deploy action only adds and overwrites files. It does not remove files that no longer exist in your build, so renamed or deleted pages linger in the bucket. If this bothers you, replace the Deploy stage with a CodeBuild step that runs aws s3 sync . s3://YOUR_BUCKET --delete, and give that role s3:ListBucket and s3:DeleteObject on the site bucket.
A missing page returns a 403 instead of a 404. Because the policy only allows GetObject, S3 cannot tell the difference between a missing key and a forbidden one, so it reports 403. Your 404.html content is still shown. Granting public s3:ListBucket would fix the status code, but it also lets anyone list your file names, so I would leave it off.
The first pipeline run fails at Source. That is almost always the GitHub connection still being in the Pending state. Authorize it and release the change again.
Nested routes do not work without the trailing slash setting. If you remove trailingSlash: true, Next.js exports about.html instead of about/index.html, and /about will not resolve on the S3 website endpoint.
The website endpoint URL looks different in some regions. Some regions use a dot and others use a dash between s3-website and the region name. That is why the Terraform output builds the URL from the resource attribute instead of hard-coding it.
Where to Go Next#
When this prototype grows up, here is the upgrade path, roughly in order of impact:
- Put CloudFront in front and make the bucket private with Origin Access Control. You get HTTPS, HTTP/2 and HTTP/3, edge caching, and security headers.
- Add a custom domain with an ACM certificate and Route 53 records.
- Store Terraform state remotely in a versioned S3 bucket with locking, so changes are safe and shareable.
- Enable S3 versioning on the website bucket for easy rollbacks.
- Add a manual approval stage between Build and Deploy for production releases.
- Send pipeline notifications to Slack or email through Amazon SNS or AWS Chatbot.
Cleaning Up#
To remove everything, empty the website bucket first, then destroy the stack:
aws s3 rm "s3://$(terraform output -raw site_bucket)" --recursive
terraform destroyWrapping Up#
With about six small Terraform files and a ten-line build spec, you now have a complete continuous deployment pipeline: push to GitHub, and a few minutes later your Next.js site is live on S3. No servers, no containers, and very little to maintain. It is the quickest route from a repository to a working URL on AWS, and a perfect foundation to build on.
If you try it and run into anything I did not cover, I would love to hear about it.
Related reading
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.
AWSTerraformCloudFrontS3
12 min readBefore 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 readFrom 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