Search code examples
reactjsamazon-s3next.jsamazon-cloudfront

How to render dynamic Next.js paths on static S3/CloudFront website hosting?


Summary

I'm trying to setup Next.js with static website hosting on S3 and CloudFront. For the most part it works but I'm having trouble with dynamic routes.

My directory structure looks like this.

pages/
  index.js
  about.js
  [id].js

Currently my Next.js config is set to trailingSlash: true so when I run next build && next export my exported static files look like this.

out/
  index.html
  about/
    index.html
  [id]/
    index.html

This means that when I visit "123456.cloudfront.net" or "123456.cloudfront.net/about/" the correct index.html is displayed. However when I visit "123456.cloudfront.net/1/", I obviously get an error message instead of out/[id]/index.html.

Caveats

The id pages are added, removed and updated regularly, so I don't want to generate them at build time using getStaticProps and getStaticPaths.

Solutions I've considered

  • I tried routing the S3 error document to out/index.html in the hopes that it would load the home page, run the JavaScript, recognise the path and end up showing the correct [id] page but it just stays on the home page.
  • I've considered trying a solution with Lambda@Edge to load the correct page but anytime I add or change paths in my application, I would probably need to update the lambda which seems messy.

Am I missing something?


Solution

  • After doing some more reading into this, I realised that serverless next.js is basically aimed at solving this same problem. It hosts your Next.js app in an s3 bucket and then uses a combination of CloudFront behaviours and Lambda@Edge to route your requests to the correct place.

    It also includes support for a lot of other Next.js features, so it looks like that's the way to go for now.