Logo
Published on

Next.js URLs break when hosting on CloudFront and S3

Authors
  • avatar
    Name
    Bobbie Couhbor
    Twitter

This blog is a Single Page Application (SPA) created using Next.js. One of the challenges I faced when hosting the site using CloudFront and S3, was trying to access non-root URLs (or even refresh the page) directly, resulting in a
403 - Access Denied error from CloudFront. After some troubleshooting, I begun a process of elimination, by removing CloudFront from the equation. I switched to an s3 hosted site (without CloudFront) which resulted in getting 404 - Page not found errors.

After some research, I found that Next.js does not include trailing slashes for URLs by default, when exporting a site. According to the documentation, the trailingSlash property needs to be set appropriately in next.config.js:

module.exports = {
  trailingSlash: true,
}

Once set this is set, exporting a site will include the trailing slash for all URLs, which will result in index.html being served within that directory and the URLs working as you would expect them to. This will only work if your CloudFront origin is an S3 website endpoint, and not the S3 Bucket Origin. If you must use the S3 Bucket Origin (maybe you don't want a publicly accessible S3 bucket), you'll need to use Lambda@Edge triggers in CloudFront.

Too much effort in my case!