Deploying React and Next.js Applications Using AWS Infrastructure
Static export, a Node server or containers: matching your Next.js features to the right AWS hosting model.
- aws
- next.js
- react
- deployment
On this page ยท 15 sections
"How do I deploy this to AWS?" has several valid answers, and the right one depends less on AWS than on your app: does it need a server at request time? A plain React single-page app, a statically exported Next.js site and a fully server-rendered Next.js application have very different hosting needs. This guide maps each type of app to a sensible AWS architecture, with the trade-offs, so you do not pay for infrastructure you do not need or lose features you do.
Step 1: Classify your app
No server needed at request time
- 1Build static files
React build or Next.js export
- 2Upload to S3
private bucket
- 3Serve through CloudFront
HTTPS, caching, custom domain
Server needed at request time
- 1Build the server
Next.js standalone output
- 2Package in a container
pushed to ECR
- 3Run on ECS, EC2 or Amplify
behind a load balancer
| App type | Needs a server? | Good fit on AWS |
|---|---|---|
| React SPA (Vite, CRA) | No | S3 + CloudFront |
Next.js with output: "export" | No | S3 + CloudFront |
| Next.js with SSR, route handlers, proxy, ISR or image optimization | Yes | ECS Fargate, EC2 or Amplify Hosting |
| Mixed: static marketing site + separate API | Split them | Static on S3/CloudFront, API on a server |
Option A: React SPA on S3 + CloudFront
A single-page app is a folder of static files. This is the simplest and cheapest setup.
- 1Build
npm run build produces dist/
- 2Upload
aws s3 sync to a private bucket
- 3CloudFront
HTTPS, caching, custom domain
- 4SPA fallback
403/404 returns index.html with 200
The pieces (private bucket with Origin Access Control, certificate in us-east-1, error mappings and cache headers) are covered in the guide on CloudFront with S3. The deploy script is short:
npm run buildaws s3 sync dist "s3://$BUCKET" --delete --exclude "index.html" \ --cache-control "public,max-age=31536000,immutable"aws s3 cp dist/index.html "s3://$BUCKET/index.html" --cache-control "no-cache"aws cloudfront create-invalidation --distribution-id "$DISTRIBUTION_ID" --paths "/index.html"Option B: Next.js static export on S3 + CloudFront
If your site can be fully prerendered, export it:
// next.config.tsimport type { NextConfig } from "next";const nextConfig: NextConfig = { output: "export", images: { unoptimized: true }, // the default image optimizer requires a server trailingSlash: true, // /about/ becomes about/index.html};export default nextConfig;next build writes the site to out/. Upload that folder exactly like Option A. Because each route is its own HTML file, add the CloudFront Function that rewrites /about/ to /about/index.html (shown in the CloudFront guide).
What you give up with a static export:
- Server-side rendering of dynamic requests and anything depending on cookies or headers at request time.
- Route Handlers and API routes that run on a server.
- Proxy (formerly middleware), including redirects and rewrites that depend on request data.
- Incremental static regeneration; content updates require a rebuild and redeploy.
- The built-in image optimizer.
Dynamic behavior moves to the client (fetching from a separate API) or to build time. Check your version's documentation for the current list of unsupported features before committing to this path.
Option C: Server-rendered Next.js in a container
When you need the full framework, run the Node.js server. Build a small image using the standalone output:
// next.config.tsconst nextConfig: NextConfig = { output: "standalone", // minimal server bundle for deployment};# DockerfileFROM node:22-alpine AS depsWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciFROM node:22-alpine AS buildWORKDIR /appCOPY --from=deps /app/node_modules ./node_modulesCOPY . .RUN npm run buildFROM node:22-alpine AS runWORKDIR /appENV NODE_ENV=productionENV PORT=3000ENV HOSTNAME=0.0.0.0RUN addgroup -S app && adduser -S app -G appCOPY --from=build /app/.next/standalone ./COPY --from=build /app/.next/static ./.next/staticCOPY --from=build /app/public ./publicUSER appEXPOSE 3000CMD ["node", "server.js"]Why this shape: a multi-stage build keeps dev dependencies out of the final image, the standalone output includes only the files the server needs, a non-root user limits damage if the process is compromised, and HOSTNAME=0.0.0.0 makes the server reachable from outside the container.
Run the container on ECS Fargate
The usual layout is:
- 1CloudFront
HTTPS, caches /_next/static
- 2Application Load Balancer
health checks, TLS to the app
- 3ECS Fargate service
2+ tasks across availability zones
- 4ECR image
pushed by your CI pipeline
- Push the image to Amazon ECR.
- Create an ECS cluster and a Fargate service with a task definition (CPU, memory, port 3000, environment variables and secrets from Secrets Manager or Parameter Store).
- Put the service behind an Application Load Balancer with a health check path such as
/api/health(create a lightweight route for it). - Run at least two tasks in different availability zones for resilience.
- Optionally front the load balancer with CloudFront, caching
/_next/static/*for a long time and passing dynamic requests through.
Deployments update the service with a new task definition revision; ECS replaces tasks gradually while the load balancer keeps traffic on healthy ones.
Option D: Next.js on a single EC2 instance
A single VM is the simplest server option for small projects: run the standalone build with a process manager and put Nginx in front, exactly as in the guide on deploying Node.js to EC2. It is cheap and flexible, but you own patching, scaling and recovery, and one instance is a single point of failure.
Option E: A managed platform
AWS Amplify Hosting can build and host Next.js apps including server-rendered ones, with Git-based deployments, preview environments and managed HTTPS. Community adapters such as OpenNext also run Next.js on serverless AWS primitives. These reduce operational work at the cost of less control and platform-specific behavior, so evaluate whether the features you use are supported and how costs scale before choosing.
Handling environment variables correctly
| Kind | When it is read | Where to set it |
|---|---|---|
| Server-only secrets (database URL, API keys) | At runtime on the server | Task definition secrets, instance environment, Secrets Manager |
Browser-exposed variables (NEXT_PUBLIC_*, Vite VITE_*) | At build time, baked into the bundle | Your CI build environment |
Anything exposed to the browser is public. Never put a secret in a browser-exposed variable, and rebuild when those values change.
Caching strategy
- Fingerprinted static assets (
/_next/static/*, hashed bundles):public, max-age=31536000, immutable. - HTML and dynamic responses: short or no caching unless you deliberately cache them.
- CloudFront in front of any option gives edge caching and a single place for HTTPS, security headers and WAF rules.
Security checklist
- Keep buckets private and use Origin Access Control.
- Run containers as a non-root user and keep images updated.
- Store secrets in a secrets manager, never in the image or repository.
- Use security groups so only the load balancer reaches your tasks.
- Terminate TLS at CloudFront or the load balancer with ACM certificates.
- Use least-privilege IAM roles for tasks and for your deployment pipeline.
Cost and operations at a glance
| Option | Operations effort | Typical use |
|---|---|---|
| S3 + CloudFront | Very low | SPAs, static sites, docs |
| Amplify Hosting | Low | Teams that want managed Next.js |
| ECS Fargate | Medium | Production SSR apps that need scaling |
| EC2 | Higher | Small projects, full control |
Costs depend on traffic, region and configuration, so use the AWS pricing calculator with your own estimates instead of assuming one option is always cheapest.
Common mistakes
- Choosing static export and then discovering a needed feature is unsupported.
- Hosting an SSR app on S3 and getting a site that serves a broken shell.
- Forgetting the SPA fallback, so deep links return errors.
- Baking secrets into browser-exposed variables or Docker images.
- Running a single task or instance for a production workload.
- Skipping health checks, so the load balancer cannot detect a failed deployment.
Testing before you cut over
Deploy to a staging environment first. Check deep links and refreshes, a 404 URL, response headers and caching, the health endpoint, an image request, and anything that depends on cookies or server logic. Run a Lighthouse or WebPageTest check against staging, and rehearse a rollback.
Best practices
- Pick the simplest architecture your app's features allow.
- Keep static assets cached aggressively and HTML fresh.
- Automate builds and deploys with CI/CD, deploying a specific commit.
- Define infrastructure as code so environments are reproducible.
- Monitor errors, latency and health checks after each release.
Conclusion
The best AWS setup for a React or Next.js app is the least complex one that still supports your features. If everything can be prerendered, S3 and CloudFront are hard to beat. If you need server behavior, run the standalone build in a container behind a load balancer, or choose a managed platform that does that work for you. Decide by features first, then by how much infrastructure you want to own.
Frequently asked questions
+Can I host a Next.js app on S3?
Only a static export of it. If you set output: 'export', Next.js produces plain HTML, CSS and JavaScript that S3 and CloudFront can serve. Features that need a server at request time (server-side rendering of dynamic requests, route handlers, middleware or proxy, ISR, the default image optimizer) are not available.
+What is the best way to host a server-rendered Next.js app on AWS?
Run the Node.js server in a container or on a VM. ECS on Fargate with an Application Load Balancer is a common managed-container choice, EC2 gives the most control, and AWS Amplify Hosting is a more managed option that supports server-rendered Next.js. Pick based on how much infrastructure you want to own.
+What does output: 'standalone' do?
It makes next build produce a minimal server bundle (including only the needed dependencies) that you can run with node server.js, which keeps Docker images small.
+Do I need CloudFront if I use EC2 or containers?
Not strictly, but it is recommended. CloudFront caches static assets near users, terminates HTTPS, adds DDoS protection with AWS Shield Standard and can reduce load on your servers.
+How do I deploy a plain React (Vite) app?
Build it to static files and host them on S3 behind CloudFront, with a fallback that serves index.html for client-side routes. No server is needed.
+Where do environment variables go?
Server-only variables are provided at runtime to the server (task definition, instance environment or secrets manager). Variables exposed to the browser are baked into the build at build time, so changing them requires a rebuild.
+How do I roll out updates without downtime?
For static hosting, upload new files and invalidate the entry document. For containers, use rolling deployments behind a load balancer with health checks. On a single EC2 instance, use a process manager's graceful reload.