【Next.js】trailingSlashをtrueにするとデフォルトの404エラーが発生する

環境

  • "next": "13.0.2"

事象

next.config.jsでtrailingSlashをtrueにするとデフォルトの404エラーが発生する

next.config.mjs

const nextConfig = {
  trailingSlash: true,
}

デフォルトの404エラー

default 404 error

▼表示されてほしい404エラー

custom 404 error

原因

trailingSlashをtrueにすると、next exportした際のoutディレクトリ内のファイル名にindex.htmlが付与されるため、デフォルトの404エラーが発生する。

trailingSlash = trueの場合のoutディレクトリ

out
├── hoge
│   └── fuga
│       ├── title1
│       │   └── index.html
└── 404
    └── index.html

trailingSlash = falseの場合のoutディレクトリ

out
├── hoge
│   └── fuga
│       └── title1.html
└── 404.html

通常であれば、404.htmlがルートディレクトリ配下にあれば表示ができるが、404フォルダは以下のindex.htmlでは表示することができない。

解決策

next export後に、404フォルダのindex.htmlをルートディレクトリ配下に404.htmlの名前でコピーする。

package.json

{
  "scripts": {
    "export": "npm run build && next export",
    "postexport": "node ./scripts/post-export.js",
  }
}

post-export.js

const {
  writeFile,
  readFile,
} = require("fs").promises;
const { join } = require("path");

const main = async () => {
  const file = await readFile(join(__dirname, "../out/404/index.html"));
  await writeFile(join(__dirname, "../out/404.html"), file);
};

main();

参考