TL;DR: You can run a Next.js App Router application on AWS with Docker, ECS Fargate, an Application Load Balancer and CloudFront instead of a managed platform. This guide covers the
standalonebuild, a multi-stage Dockerfile, immutable image tags in ECR, an ECS task definition with secrets from SSM, health checks, CloudFront behaviors built on managed cache policies, a GitHub Actions pipeline that uses OIDC instead of stored AWS keys, and the settings Next.js needs when it runs on more than one container. Whether it is cheaper depends on your traffic and your team's time, so model both before migrating.
Key Takeaways
- Set
output: 'standalone'innext.config.mjsso the build traces only the files and dependencies the server needs, instead of shipping your wholenode_modules. - Explicitly copy the
publicand.next/staticfolders into your Docker runner stage, or static assets and CSS return 404. - Run the container as a non-root user, base it on a current Node.js LTS image, and deploy images by commit SHA from an ECR repository with immutable tags and scan-on-push.
- In CloudFront, cache
/_next/static/*with the managedCachingOptimizedpolicy and send everything else throughCachingDisabledwith theAllViewerorigin request policy until you have a deliberate HTML caching strategy. - With more than one container, set
NEXT_SERVER_ACTIONS_ENCRYPTION_KEYat build time, configure adeploymentId, and use a shared cache handler if you rely on ISR orrevalidateTag.
Your Next.js application started as an inexpensive prototype on a managed platform and is now handling serious traffic. The developer experience is still excellent, but usage-based charges for bandwidth, function execution and image optimization grow with every new customer, and platform limits shape how you build features.
The convenience of a git push deployment can turn into vendor lock-in when your costs, compliance requirements or data residency rules no longer fit the platform. Applications that rely heavily on Server-Side Rendering (SSR), high-bandwidth image delivery and long-running requests feel this first.
One alternative is to run the same application in containers. With AWS Elastic Container Service (ECS) on AWS Fargate, fronted by an Application Load Balancer (ALB) and Amazon CloudFront, you get horizontal scaling, AWS-native networking and IAM, and pricing you can model line by line. In exchange, you take on work the platform used to do for you.
This guide walks through that setup end to end, using current Next.js self-hosting guidance.
Preparing Next.js for Docker: The Standalone Output
By default, running next build generates a .next folder meant to be run alongside your entire node_modules directory, which often includes build tooling and dev dependencies. Copying all of that into a container makes images large, pushes slow and task startup slower.
Next.js provides an Output File Tracing feature that automatically creates a standalone folder containing only the files and dependencies strictly required for production.
Enable this by updating your next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
images: {
// Required if you use next/image with a custom loader or external URLs
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.yourdomain.com',
},
],
},
// Disable the powered-by header for security
poweredByHeader: false,
};
export default nextConfig;
With standalone enabled, we can write a multi-stage Dockerfile whose final image contains only the traced server, static assets and the Node.js runtime. This version follows the structure of the official with-docker example in the Next.js repository:
# Pin a current Node.js LTS release; update it deliberately (or pin by digest)
ARG NODE_VERSION=24-slim
# Stage 1: Install dependencies
FROM node:${NODE_VERSION} AS deps
WORKDIR /app
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; \
elif [ -f yarn.lock ]; then corepack enable yarn && yarn install --frozen-lockfile; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm install --frozen-lockfile; \
else echo "Lockfile not found." && exit 1; \
fi
# Stage 2: Build
FROM node:${NODE_VERSION} AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
# Optional build secret: a shared Server Actions key for multi-task deployments
RUN --mount=type=secret,id=server_actions_key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY \
npm run build
# Stage 3: Production runner
FROM node:${NODE_VERSION} AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
# Bind to all interfaces inside the container
ENV HOSTNAME=0.0.0.0
COPY --from=builder --chown=node:node /app/public ./public
# Writable directory for the prerender cache
RUN mkdir .next && chown node:node .next
# Traced server output plus static assets
COPY --from=builder --chown=node:node /app/.next/standalone ./
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
# The official Node.js images ship an unprivileged "node" user
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Image size depends mostly on your traced dependencies, so check it with docker image ls after the first build rather than assuming a number. A .dockerignore that excludes node_modules, .next, .git and local .env files keeps the build context small and stops secrets from leaking into the image.
Production Note: The standalone build does not automatically copy the
publicor.next/staticfolders into thestandalonedirectory (so they can ideally be served by a CDN). Because we are running a self-contained Docker image, you must explicitly copy them in the Dockerfile, as shown above. Otherwise, your static assets and CSS will return 404s.
Building and Pushing to AWS Elastic Container Registry (ECR)
Before we can provision ECS, we need a secure, private registry to store our Docker images. AWS Elastic Container Registry (ECR) integrates natively with ECS and AWS IAM.
Use the AWS CLI to create your repository. Immutable tags mean a tag such as a commit SHA can never be overwritten, so the image a task definition points at is always the image that was tested:
aws ecr create-repository \
--repository-name nextjs-enterprise-app \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--region us-east-1
For a first manual push, authenticate your local Docker daemon with ECR, then build and push an image tagged with the current commit. (Replace 123456789012 with your AWS Account ID.) After that, let CI do the pushing.
REGISTRY=123456789012.dkr.ecr.us-east-1.amazonaws.com
TAG=$(git rev-parse --short HEAD)
# Authenticate (the password is piped, never written to disk or shell history)
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin $REGISTRY
# Build and push an immutable, traceable tag instead of :latest
docker build -t $REGISTRY/nextjs-enterprise-app:$TAG .
docker push $REGISTRY/nextjs-enterprise-app:$TAG
Provisioning the ECS Fargate Cluster and Task Definition
With AWS Fargate, ECS runs your containers without you managing EC2 instances. You define CPU and memory per task, and AWS provisions and patches the underlying hosts. Scaling the number of tasks is still your decision, through ECS Service Auto Scaling policies on CPU, memory or request count.
If you would rather have a team set up and run this infrastructure with you, our DevOps and cloud deployment services cover ECS, CloudFront and CI/CD pipelines like the one below.
The core of an ECS deployment is the Task Definition. This JSON document tells ECS which image to pull, what ports to open, and which environment variables and secrets to inject.
Create a file named task-definition.json:
{
"family": "nextjs-production-task",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "1024",
"memory": "2048",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskRole",
"containerDefinitions": [
{
"name": "nextjs-app",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/nextjs-enterprise-app:REPLACED_BY_CI",
"essential": true,
"portMappings": [
{
"containerPort": 3000,
"hostPort": 3000,
"protocol": "tcp"
}
],
"environment": [{ "name": "NODE_ENV", "value": "production" }],
"secrets": [
{
"name": "DATABASE_URL",
"valueFrom": "arn:aws:ssm:us-east-1:123456789012:parameter/production/DATABASE_URL"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/nextjs-production",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}
]
}
The secrets block injects values from SSM Parameter Store (or Secrets Manager) at task start, so they never appear in the task definition or image. The execution role needs permission to read those parameters, and the CI pipeline below replaces the image placeholder with the commit-tagged image. Register the task definition with AWS:
aws ecs register-task-definition --cli-input-json file://task-definition.json
Application Load Balancer (ALB) and Health Checks
Fargate tasks are ephemeral; they receive new internal IP addresses every time they deploy or scale. An Application Load Balancer (ALB) provides a static entry point to your cluster and evenly distributes incoming traffic across your active Next.js containers.
To ensure the ALB only routes traffic to healthy containers, you must configure a Target Group with an HTTP health check. Next.js App Router makes this simple.
Create a lightweight health check route in your Next.js application at app/api/health/route.ts:
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json(
{ status: 'healthy', timestamp: new Date().toISOString() },
{ status: 200 },
);
}
Critical Warning: Do not connect to your database inside this health check endpoint. If your database has a brief latency spike, every task fails its health check at once, and ECS replaces healthy containers that could have served the requests that did not need the database. Keep the load balancer health check about whether this container can serve HTTP, and monitor dependencies separately.
When configuring your ALB Target Group (via the AWS Console, Terraform, or CLI), set the Health Check Path to /api/health, the protocol to HTTP, and the port to 3000.
Replacing Vercel's Edge Network with AWS CloudFront
A managed platform puts a CDN in front of your app automatically, caching static assets and, where headers allow, ISR pages. To get the same effect on AWS, we place Amazon CloudFront in front of the Application Load Balancer. Without it, every request for a hashed JavaScript or CSS file reaches your containers.
Next.js already sends the right headers. Hashed build assets under /_next/static get Cache-Control: public, max-age=31536000, immutable, ISR pages get s-maxage with stale-while-revalidate, and dynamically rendered pages get private, no-cache, no-store, max-age=0, must-revalidate. The safest starting point is to let CloudFront cache only what is unambiguously static, using AWS managed policies rather than a hand-written one:
{
"DefaultCacheBehavior": {
"TargetOriginId": "nextjs-alb",
"ViewerProtocolPolicy": "redirect-to-https",
"AllowedMethods": {
"Quantity": 7,
"Items": ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
},
"CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
"OriginRequestPolicyId": "216adef6-5c7f-47e4-b989-5492eafa07d3"
},
"CacheBehaviors": {
"Quantity": 1,
"Items": [
{
"PathPattern": "/_next/static/*",
"TargetOriginId": "nextjs-alb",
"ViewerProtocolPolicy": "redirect-to-https",
"CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
"Compress": true
}
]
}
}
This fragment of a distribution config uses three managed policies:
/_next/static/*usesCachingOptimized(658327ea-...). Cookies and query strings are left out of the cache key, so every user shares one cached copy of each hashed file.- Default (
*) usesCachingDisabled(4135ea2d-...) with theAllViewerorigin request policy (216adef6-...), which forwards all headers, cookies and query strings. SSR pages, route handlers and Server Actions behave exactly as they would without a CDN, and personalized pages are never cached. - Files from
public/are served at the site root (for example/logo.svg, not/public/logo.svg), so they fall through to the default behavior unless you add behaviors for their paths or move them to an S3 origin.
AllViewer forwards the viewer's Host header, which lets Next.js build correct absolute URLs and redirects. Because CloudFront then connects to the ALB using that host name, the ALB's HTTPS listener needs a certificate that covers your public domain. Caching HTML or /_next/image responses at the edge is possible, but read the Next.js CDN caching guide first: App Router responses vary on request headers that CloudFront does not include in the cache key unless you configure them.
Automating the Deployment with GitHub Actions
A successful migration keeps the "git push to deploy" developer experience. AWS runs the infrastructure, and GitHub Actions runs the CI/CD pipeline.
The workflow below builds the image, pushes it to ECR and deploys a new task definition using the official AWS actions. It authenticates with GitHub's OIDC provider and an IAM role (role-to-assume), so no long-lived AWS access keys are stored in GitHub secrets. Create the IAM OIDC identity provider and a deploy role whose trust policy only allows your repository and branch.
Create a .github/workflows/deploy.yml file in your repository:
name: Deploy Next.js to ECS
on:
push:
branches:
- main
env:
AWS_REGION: us-east-1
ECR_REPOSITORY: nextjs-enterprise-app
ECS_CLUSTER: production-cluster
ECS_SERVICE: nextjs-service
ECS_TASK_DEFINITION: .aws/task-definition.json
CONTAINER_NAME: nextjs-app
permissions:
id-token: write # Required to request the OIDC token
contents: read
jobs:
deploy:
name: Build and Deploy
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Configure AWS credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Build, tag, and push image to Amazon ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: ${{ github.sha }}
# Same key for every build and every container (see "Running more than one task")
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
run: |
docker build \
--secret id=server_actions_key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY \
-t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT
- name: Fill in the new image ID in the Amazon ECS task definition
id: task-def
uses: aws-actions/amazon-ecs-render-task-definition@v1
with:
task-definition: ${{ env.ECS_TASK_DEFINITION }}
container-name: ${{ env.CONTAINER_NAME }}
image: ${{ steps.build-image.outputs.image }}
- name: Deploy Amazon ECS task definition
uses: aws-actions/amazon-ecs-deploy-task-definition@v2
with:
task-definition: ${{ steps.task-def.outputs.task-definition }}
service: ${{ env.ECS_SERVICE }}
cluster: ${{ env.ECS_CLUSTER }}
wait-for-service-stability: true
With this pipeline, when a developer merges a PR into main, GitHub Actions builds the standalone Next.js image, pushes it to ECR tagged with the commit SHA, renders a task definition that points at that tag, and starts a rolling deployment in ECS. With the service's minimumHealthyPercent at 100, ECS starts new tasks before stopping old ones. The wait-for-service-stability: true flag makes the workflow wait until the new tasks are running and healthy in the target group. Enable the ECS deployment circuit breaker with rollback so a release that never becomes healthy is rolled back automatically.
The --secret flag passes the key to the Dockerfile's RUN --mount=type=secret build step, so it does not appear in build arguments or image history. Next.js embeds the key in the build output, so treat the image itself as sensitive and keep the repository private.
Running More Than One Task
A single container works with Next.js defaults. As soon as ECS runs two or more tasks, the Next.js self-hosting guide calls out three settings:
| Concern | What goes wrong | Setting |
|---|---|---|
| Server Actions encryption key | "Failed to find Server Action" when requests hit different builds | Same NEXT_SERVER_ACTIONS_ENCRYPTION_KEY (base64, 16/24/32 bytes) at build time |
| Version skew during rollouts | Clients request assets or actions the new tasks do not have | deploymentId in next.config.mjs, for example set from the commit SHA |
ISR and revalidateTag | Each task has its own cache, so tasks serve different versions | cacheHandler backed by Redis or S3, with cacheMaxMemorySize: 0 |
The Next.js docs also recommend a reverse proxy in front of the Node.js server to handle malformed requests, slow clients and request size limits. In this setup, the ALB and CloudFront fill that role, and AWS WAF can add rate limiting.
The Financial Impact of Self-Hosting
The developer experience of managed platforms is excellent for teams prioritizing speed to market over unit economics. As traffic grows, it is worth checking whether that trade still holds.
By running your CDN layer (CloudFront), compute layer (ECS) and container images yourself, you replace a bundled platform price with individual AWS line items: Fargate vCPU and memory hours, ALB hours and capacity units, CloudFront requests and data transfer out, NAT gateway or VPC endpoint charges, CloudWatch logs and ECR storage. Price those with the AWS Pricing Calculator using your real traffic, and add the engineering time for on-call, patching and upgrades. For high, steady traffic the AWS total is often lower; for small or spiky workloads a managed platform can still be cheaper overall.
Moving to AWS does not mean giving up automated deployments or edge caching. It means you own their configuration, including the parts in this guide that a platform used to handle silently.
Sources
- Next.js docs: How to self-host your Next.js application (caching headers, multi-instance settings, reverse proxy, streaming)
- Next.js with-docker example Dockerfile
- Amazon CloudFront: Managed cache policies
- Amazon CloudFront: Managed origin request policies
- aws-actions/configure-aws-credentials (OIDC with
role-to-assume)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Do I lose Next.js features when I self-host instead of using Vercel?
Most App Router features work in a Node.js server, including Server Components, streaming, Proxy (called middleware before Next.js 16), and incremental static regeneration. What you rebuild yourself is the platform around it: CDN caching, image optimisation capacity, preview deployments, and a shared cache, encryption key and deployment ID when you run several instances.
What does output standalone do?
It traces the files your app actually needs and produces a minimal server.js bundle, so the Docker image contains only production dependencies. Images are much smaller and start faster.
Why put CloudFront in front of ECS?
CloudFront caches static assets and cacheable pages at edge locations, terminates TLS close to users, and reduces load on your containers. Configure it to forward only the headers and cookies your app needs, or caching becomes ineffective.
Is self-hosting Next.js on AWS always cheaper?
Not always. It usually saves money at high, steady traffic, but you take on the work of running the infrastructure: deployments, scaling, monitoring, and security patching. Compare the full cost, including engineering time, before migrating.
