How To Deploy Next JS App to AWS S3
Deploying a Next.js application to AWS S3 is a popular approach for
developers looking to host static websites or pre-rendered Next.js apps
cost-effectively. While AWS offers a range of hosting options like
Elastic Beanstalk, EC2, and Amplify, using Amazon S3
(Simple Storage Service) combined with CloudFront offers a
lightweight, fast, and scalable solution for static Next.js websites.
In this comprehensive guide, we'll walk you through the complete process
of deploying a Next.js app to AWS S3, from building your project to
configuring S3, setting up CloudFront for global delivery, and applying
best practices for performance and security.
By the end of this guide, you'll have a fully deployed Next.js site
hosted on AWS S3 and distributed globally using AWS CloudFront.
π§ Understanding AWS S3 Hosting for Next.js
Before we dive into deployment steps, it's important to understand how
AWS S3 works.
Amazon S3 is an object storage service designed to store and
retrieve any amount of data. While it's commonly used for file storage,
it also supports static website hosting, making it perfect for Next.js
static exports.
However, Next.js supports both server-side rendering (SSR) and
static site generation (SSG). Since AWS S3 is a static hosting
solution, it can only host SSG or statically exported Next.js apps
--- not SSR apps. If your app uses SSR, you'll need AWS Lambda or
Amplify instead.
Suitable Scenarios for S3 Hosting
Use AWS S3 if your Next.js app: - Is generated statically usingnext export. - Doesn't rely on server-side rendering or API routes. -
Is primarily a marketing site, blog, portfolio, or documentation
platform.
If your app fits this use case, AWS S3 will be a cost-effective and
highly performant choice.
βοΈ Prerequisites
Before you start, ensure you have the following ready:
- AWS Account: You can create one at
aws.amazon.com.\ - AWS CLI installed: The AWS Command Line Interface helps automate
deployment.\ - Node.js and npm installed: Required for building your Next.js
project.\ - A Next.js project: You can create one if you don't have it
already.
To verify your installations:
node -v
npm -v
aws --version
If you don't have a Next.js project yet, you can quickly set one up
with:
npx create-next-app my-nextjs-app
cd my-nextjs-app
npm run dev
After testing locally, we'll prepare it for deployment.
π Step-by-Step Guide to Deploy a Next.js App on AWS S3
Step 1: Prepare Your Next.js App for Static Export
Since AWS S3 hosts static sites, you must export your Next.js app into
static files. Open your package.json and ensure your build and export
scripts look like this:
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next export",
"start": "next start"
}
Run the following commands to generate static files:
npm run build
npm run export
This command creates an out/ directory containing your static
HTML, CSS, and JavaScript files.
Step 2: Create an S3 Bucket
- Sign in to your AWS Management Console.\
- Navigate to S3 β Create bucket.\
- Choose a unique name for your bucket (e.g.,
my-nextjs-app).\ - Select a region close to your users.\
- Uncheck "Block all public access" --- you'll need to make the
site public.\ - Click Create bucket.
Your bucket is now ready to store static files.
Step 3: Enable Static Website Hosting
- Go to your new S3 bucket.\
- Click Properties β Scroll down to Static website hosting.\
- Select Use this bucket to host a website.\
- Enter
index.htmlas the Index document and404.htmlfor the
Error document.\ - Save changes.
Your S3 bucket is now ready to serve static web pages.
Step 4: Upload the Exported Next.js Files
You can upload files manually or through the AWS CLI.
Option 1: Upload via AWS Console
- Open your S3 bucket.\
- Click Upload β Add files and Add folder.\
- Upload all files from your
out/directory.\ - Click Upload.
Option 2: Upload via AWS CLI
From your terminal, navigate to your project directory and run:
aws s3 sync ./out s3://your-bucket-name --acl public-read
This command uploads all static files to your S3 bucket and makes them
publicly readable.
Step 5: Set Permissions for Public Access
To make your site publicly accessible:
- Go to Permissions in your S3 bucket.\
- Under Bucket policy, click Edit policy and paste the
following JSON:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::your-bucket-name/*"]
}
]
}
Replace your-bucket-name with your actual bucket name.
Click Save to apply the policy.
Step 6: Access Your Website
Go to Properties β Static website hosting, and you'll find a URL
like:
http://your-bucket-name.s3-website-us-east-1.amazonaws.com
Open this link in your browser --- congratulations! Your Next.js app is
now live on AWS S3. π
π Step 7: (Optional) Add CloudFront for Global CDN
While your S3-hosted site is live, it may load slower for users in
distant regions. To improve global performance, use Amazon
CloudFront, AWS's Content Delivery Network (CDN).
- Go to AWS CloudFront in your console.\
- Click Create Distribution.\
- Under Origin domain, select your S3 bucket.\
- Set Viewer protocol policy to "Redirect HTTP to HTTPS."\
- Leave other defaults as is and click Create Distribution.
After CloudFront finishes deploying, you'll receive a distribution
domain like:
https://d123abc456def.cloudfront.net
You can now access your Next.js site globally via this CDN-powered URL.
Connect a Custom Domain (Optional)
To make your site more professional, connect a custom domain via Route
53:
- Create a Hosted Zone for your domain.\
- Add an Alias record pointing to your CloudFront distribution.\
- Configure your domain's DNS settings with your registrar.
Once DNS propagation completes, your app will be available on your
custom domain.
π§© Automating Deployments with GitHub Actions (Optional)
You can automate deployment using GitHub Actions to push changes to
AWS S3 every time you update your repository.
Create a .github/workflows/deploy.yml file in your repo:
name: Deploy to AWS S3
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install dependencies
run: npm install
- name: Build Next.js app
run: npm run build && npm run export
- name: Deploy to S3
uses: jakejarvis/s3-sync-action@v0.5.1
with:
args: --acl public-read --follow-symlinks --delete
env:
AWS_S3_BUCKET: ${{ secrets.AWS_S3_BUCKET }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: 'us-east-1'
SOURCE_DIR: './out'
This setup ensures your AWS S3 bucket updates automatically whenever you
push changes to the main branch.
π Best Practices for Hosting Next.js on AWS S3
- Use HTTPS with CloudFront: Always serve your site securely using
HTTPS.\ - Cache Optimization: Use CloudFront caching to reduce load
times.\ - Set Up Versioning: Enable S3 versioning to avoid accidental data
loss.\ - Use Environment Variables Carefully: Don't expose sensitive data
in client-side builds.\ - Enable Compression: Use gzip or Brotli compression for static
assets.\ - Monitor Performance: Use AWS CloudWatch to monitor site traffic
and performance.
π§° Troubleshooting Common Issues
1. "Access Denied" Error
Check your bucket policy and object permissions. Ensure files
are publicly readable.
2. Missing CSS or JS
Ensure all assets are inside the out/ directory before uploading.
The next export command should generate all files correctly.
3. Incorrect MIME Types
If your stylesheets or JavaScript aren't loading, verify your
Content-Type headers in S3 match the correct MIME types.
4. Custom 404 Pages Not Working
Ensure your Error document is set to 404.html under Static
website hosting settings.
π‘ Final Thoughts
Deploying your Next.js app on AWS S3 is a cost-effective and
efficient solution for static websites. By combining S3 with CloudFront,
you can ensure fast, reliable, and globally distributed content delivery
without managing servers.
This approach is ideal for blogs, portfolios, marketing sites, and
documentation platforms that rely on static content. Plus, with the
addition of CI/CD automation, you can streamline updates and keep your
site fresh effortlessly.
If you're building a Next.js or MERN stack project and want
professional assistance in development, deployment, or optimization,
consider hiring AAMAX. AAMAX is a full-service
digital marketing and web development company specializing in MERN
Stack Development, SEO, and Digital Marketing Services. Their
expert team ensures your web applications are secure, optimized, and
ready for growth.
With AAMAX's expertise and AWS's infrastructure, your Next.js app can
achieve unmatched performance and scalability.
Want to publish a guest post on aamax.co?
Place an order for a guest post or link insertion today.
Place an Order