Export NextJS Site To Static HTML Without 404 Errors

Tech

  • NextJS 14

I prefer to use NextJS + MUI even for simple static websites such as this one. Some might scream heresy, but I am already proficient in them, have all the tools configured and find the workflow pleasant. NextJS allows exporting to simple static files with some caveats. Web server of your choice will then handle the serving.

This works great except that NextJS exports the files in "blog.html" instead of "blog/index.html" form by default. So when you visit the hompage example.com, everything works perfectly. However if you navigate to a different page, e.g. example.com/blog, copy the address and paste it into the browser again, you'll get a 404 Not Found error.

There's several ways to go about it. First would be to use your web server rewrite rule to append ".html" to all pages except homepage. Good, but I am not fan of rewrites. Second (and in my opinion better) solution is to configure NextJS to append trailing slashes to all the routes. The official documentation has a lone sentence for the "trailingSlash" setting:

When used with output: "export" configuration, the /about page will output /about/index.html (instead of the default /about.html).

So go to the next.config.mjs file, include these 2 settings in there and you'll be set:

1// next.config.mjs
2const nextConfig = {
3    output: 'export',
4    trailingSlash: true,
5    ... // rest of the settings
6}