Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next.js export static - S3 - routing fails on page reload

I'm deploying a next.js app as a static export, to an s3 bucket configured for static website hosting.

I use next's build and export commands to generate the out/ directory and then copy that into my s3 bucket

The bucket then contains some files, for simplicity lets say there's just index.html and about.html

The problem is when a user hits index.html via www.website.com then navigates to www.website.com/about everything works, but reloading www.website.com/about fails of course.

www.website.com/about.html finds the correct asset to render the site however

Is there a way to export a static next.js app, host on s3, and have requests to /about proxy /about.html ?

As always, thanks for looking, and thanks even more for participating.

like image 507
James Avatar asked Aug 10 '19 01:08

James


2 Answers

On your next.config.js file at the root of the project.

module.exports = {
    trailingSlash: true,
}

Now you can create your pages (e.g. about.jsx) inside the pages directory and Next will create a folder with the file name with an index.html file inside of it when you run the export command.

Give it a try, worked fine here.

like image 118
machineghost Avatar answered Oct 14 '22 11:10

machineghost


The best solution I've arrived at so far, inspired by this gist: https://gist.github.com/rbalicki2/30e8ee5fb5bc2018923a06c5ea5e3ea5

Basically when deploying the build to the s3 bucket, you can simply rename the .html files to have no .html suffix, ex: www.bucket.com/about.html -> www.bucket.com/about and now both SSR & CSR routing work as expected.

The resulting files have Content-Type: text/html despite not having the suffix, I don't know if this is problematic or not.

like image 7
James Avatar answered Oct 14 '22 10:10

James