How to host next.js static website in an AWS S3 bucket
— next.js, static website hosting, AWS S3 — 2 min read
Problem you will faced
- s3 cannot run sever side rendering and it only can serve static file
- if user refresh the page then it might hit error
we will break down later to see how to solve the problem
What is AWS S3 (Object Storage):
- Cost: Primarily based on storage usage (GB/month) and data transfer out. S3 offers tiered pricing, with lower rates for larger storage volumes.
- Use Cases: Ideal for storing static files, images, videos, and other content that can be served directly.
- Benefits: Highly scalable, durable, and available. Can be used with CloudFront for CDN (Content Delivery Network) to enhance performance.
- Example: Hosting a static website or storing user uploads
- limitation: it only can host static website
How to host next.js static site to s3 bucket
-
in next.config.js you need to add few things
const nextConfig = {output: "export", // generate static filetrailingSlash: true, // it will hep you to generate the file by page_name/index.html instead of page_name.htmldistDir: "build", // Change output directory from 'out' to 'build'};lets break down 1 by 1
output: "export": helps you to generate a static webpage that contain only static file that can store in s3 bucket such as .js, .css, .html and your imagestrailingSlash: true(important else when you refresh page you will get error): after you run this command your output after build will be change- Next.js will generate pages like
out/about/index.html. - Links will be to
/about/. - S3's "Index document" setting will naturally work for these paths if directly accessed (e.g., if public).
- Next.js will generate pages like
distDir: "build"(optional): this is only changing your build directory to the named you given
After you bulid he file just put the build folder to AWS S3 and point your domain to AWS S3
Extra (Why we pick this solution)
Component Design
- you are familier with react architechture and want to leverage the component design to a static page
Faster loading speed
- next.js provide us static export and only loading the chuck it need compare to the CSR we will load a huge chuck of index.js
- the static file can be using cdn that allow user to load faster on the file you host in s3 which can improve the perfromance
SEO friendly
- it wil generate the html file that let search engine crawler to know the content about the page for better ranking and indexing
Cost Efficency
- using s3 bucket is much more cost friendly then you spin up an instance that need to calculate by hours