Hamza Janzaib avatar
AboutResumeProjectsWorkBlogContact
Home/Blog/AWS, Deployment & DevOps/Deploying React and Next.js Applications Using AWS Infrastructure

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.

By Hamza JanzaibNovember 28, 202614 min readAdvanced
Paste it into ChatGPT, Claude or any AI assistant.
  • aws
  • next.js
  • react
  • deployment
On this page ยท 15 sections
  • Step 1: Classify your app
  • Option A: React SPA on S3 + CloudFront
  • Option B: Next.js static export on S3 + CloudFront
  • Option C: Server-rendered Next.js in a container
  • Run the container on ECS Fargate
  • Option D: Next.js on a single EC2 instance
  • Option E: A managed platform
  • Handling environment variables correctly
  • Caching strategy
  • Security checklist
  • Cost and operations at a glance
  • Common mistakes
  • Testing before you cut over
  • Best practices
  • Conclusion

"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

  1. 1Build static files

    React build or Next.js export

  2. 2Upload to S3

    private bucket

  3. 3Serve through CloudFront

    HTTPS, caching, custom domain

Server needed at request time

  1. 1Build the server

    Next.js standalone output

  2. 2Package in a container

    pushed to ECR

  3. 3Run on ECS, EC2 or Amplify

    behind a load balancer

Decide by features first: does any page need a server when it is requested?
App typeNeeds a server?Good fit on AWS
React SPA (Vite, CRA)NoS3 + CloudFront
Next.js with output: "export"NoS3 + CloudFront
Next.js with SSR, route handlers, proxy, ISR or image optimizationYesECS Fargate, EC2 or Amplify Hosting
Mixed: static marketing site + separate APISplit themStatic 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.

  1. 1Build

    npm run build produces dist/

  2. 2Upload

    aws s3 sync to a private bucket

  3. 3CloudFront

    HTTPS, caching, custom domain

  4. 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:

bash
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:

ts
// 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:

ts
// next.config.tsconst nextConfig: NextConfig = {  output: "standalone", // minimal server bundle for deployment};
dockerfile
# 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:

  1. 1CloudFront

    HTTPS, caches /_next/static

  2. 2Application Load Balancer

    health checks, TLS to the app

  3. 3ECS Fargate service

    2+ tasks across availability zones

  4. 4ECR image

    pushed by your CI pipeline

  1. Push the image to Amazon ECR.
  2. 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).
  3. Put the service behind an Application Load Balancer with a health check path such as /api/health (create a lightweight route for it).
  4. Run at least two tasks in different availability zones for resilience.
  5. 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

KindWhen it is readWhere to set it
Server-only secrets (database URL, API keys)At runtime on the serverTask definition secrets, instance environment, Secrets Manager
Browser-exposed variables (NEXT_PUBLIC_*, Vite VITE_*)At build time, baked into the bundleYour 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

OptionOperations effortTypical use
S3 + CloudFrontVery lowSPAs, static sites, docs
Amplify HostingLowTeams that want managed Next.js
ECS FargateMediumProduction SSR apps that need scaling
EC2HigherSmall 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.

Further reading

  • nextjs.org/docs/app
  • docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html
  • docs.aws.amazon.com/ec2/

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202615 min readBeginner

Hosting a Static Website on AWS S3

Create a bucket, allow public reads, enable website hosting and deploy a build with one CLI command.

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

Next.js, React & TypeScriptNovember 28, 202612 min readIntermediate

Solving Server and Client Component Problems in Next.js

The errors you will actually hit with Server and Client Components, why they happen and how to fix them.

Built by Hamza Janzaib

PrivacyTerms