💬

App Routerの落とし穴 HTMLタグ忘れる編 [Next.js]

2023/02/16に公開

App Routerは、まだまだエラー対処法の情報が少ない。筆者は、ルートのHTMLタグを忘れるという根本的なミスを犯してしまったのに、ビルドが通ってしまい、原因にたどり着けず時間を浪費してしまった。

問題のファイルがこちら

app/layout.tsx (間違っているので真似するな)
import Footer from '@/components/Footer';
import Header from '@/components/Header';
import { ReactNode } from 'react';
import '@/styles/globals.css';

export default async function Layout({ children }: { children: ReactNode }) {
  return (
    <>
      <Header />
      <div className="container">{children}</div>
      <Footer />
    </>
  );
}

これは app/layout.tsx なので、何もしなければ全ページで使われるレイアウトである。

v13.4.4現在、ローカルでは表示できるし、ビルドも通ってしまう

だが、根本的に間違えている。

ビルド語のエラー

ビルドしたサイトを動かすと、一切の描画に失敗する。エラー内容:

正解

app/layout.tsx
import Footer from '@/components/Footer';
import Header from '@/components/Header';
import { ReactNode } from 'react';
import '@/styles/globals.css';

export default async function Layout({ children }: { children: ReactNode }) {
  return (
+    <html lang="ja">
+      <body>
        <Header />
        <div className="container">{children}</div>
        <Footer />
+      </body>
+    </html>
  );
}

htmlbodyを忘れていた。

https://beta.nextjs.org/docs/routing/pages-and-layouts#root-layout-required

The root layout must define <html> and <body> tags since Next.js does not automatically create them.

ドキュメントには「必ず書くように」と書いてあるので、忘れていた俺が悪いのだが...

指摘と現状

https://github.com/vercel/next.js/issues/41896#issuecomment-1292643524

We could however provide a better warning for this type of error, so we are keeping this issue to track.

HTMLとBODYが無いですよというイシューが立っていて、「layout.tsxがそれらを返さないといけないんですよ」「でも、より良い警告が出せるだろうから」とオープンのままになっている。

気づいた経緯

最初、直接原因がわからず戸惑った。この手のエラーは主に以下の原因が多い。

  • HTML構造に誤りがある
  • サーバーとクライアントで齟齬が生じるロジックがある
    • もっぱらDateに関するミスが多い

開発用サーバーでのエラー

そういえば、表示できているからと、コンソールをしっかり読まずにビルドしていた。

ちゃんとローカルのコンソールを見ると、invariant expected app router to be mounted という警告が出ていた。

https://stackoverflow.com/a/74601107

このエラーで調べることで、ようやく htmlbodyを忘れている事に気づいたのだった。

根本的な対処法

App Routerへの以降で、1からコードを書かない。

代わりに、create-next-app でアプリを作成し、appのコードをコピーする。

その他の落とし穴

App Routerの反面教師となるべく、色々な間違いを記事に残している。

https://zenn.dev/temasaguru/articles/0191cf919bd0a3

https://zenn.dev/temasaguru/articles/5d037825dc192f

https://zenn.dev/temasaguru/articles/6e6b47a34d9855

Discussion