← back to blog
1 min read

Hosting a Next.js site on S3 and CloudFront for pennies

How to serve a static Next.js export from a private S3 bucket behind CloudFront, with HTTPS, caching, and a Lambda API on the same domain.

  • AWS
  • Next.js
  • CloudFront
  • Serverless

Static sites are the sweet spot for personal portfolios and blogs: they are fast, cheap, and trivially cacheable. Here is the architecture I use to serve a Next.js export from AWS without paying for an always-on server.

Why CloudFront in front of S3

S3 static website hosting only serves plain HTTP. To get HTTPS on a custom domain, and to keep the bucket private, you put CloudFront in front with Origin Access Control (OAC). Only the distribution can read the bucket.

CloudFront is also generous on cost. The perpetual free tier covers 1 TB of data transfer out and 10 million HTTPS requests per month, and origin fetches from S3 to CloudFront are free.

One domain for the site and the API

The nice trick is path-based routing at the edge:

  • the default behavior serves static files from S3
  • a /api/* behavior forwards to an API Gateway origin

That keeps the browser talking to a single origin, so there is no CORS to manage.

// A client-side fetch that CloudFront routes to Lambda
const res = await fetch("/api/views/my-post", { method: "POST" });
const { views } = await res.json();

The takeaway

Static export plus CloudFront plus a small Lambda gives you great SEO, great performance, and a bill that rounds to zero for a personal site.

Comments

    Leave a comment