Skip to content
Go back

Implementing CloudFront Caching for Next.js Apps

Implementing CloudFront Caching for Next.js Apps

Introduction

AWS CloudFront CDN accelerates content delivery by caching assets at edge locations. This guide configures CloudFront for Next.js.

Prerequisites

Step 1: Build and Export Static Site

For SSG:

npm run build
npm run export
# Upload 'out/' directory to S3 bucket

Step 2: Create S3 Origin

Enable static website hosting on S3 bucket.

Step 3: Create CloudFront Distribution

aws cloudfront create-distribution \
  --origin-domain-name mybucket.s3.amazonaws.com \
  --default-root-object index.html \
  --default-cache-behavior TargetOriginId=S3Origin,ViewerProtocolPolicy=redirect-to-https,MinTTL=0,DefaultTTL=86400,MaxTTL=31536000,CachedMethods=GET,HEAD

Step 4: Configure Cache Behaviors

Add behaviors for _next/static, API routes, etc.:

aws cloudfront create-cache-behavior \
  --distribution-id E1234567890 \
  --path-pattern "_next/static/*" \
  --target-origin-id S3Origin \
  --viewer-protocol-policy redirect-to-https \
  --min-ttl 86400 \
  --allowed-methods GET,HEAD

Step 5: Invalidation

Invalidate on deploy:

aws cloudfront create-invalidation \
  --distribution-id E1234567890 \
  --paths "/index.html" "/_next/*"

Summary

CloudFront improves Next.js performance by caching static assets globally, reducing latency. Configure cache behaviors and use invalidations for smooth updates.


Share this post on:

Previous Post
Using AWS ECS for Containerized Applications
Next Post
Monitoring AWS Lambda Performance with CloudWatch