かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Next.js link タグで stylesheet を追加するときは next/document を使う

タイトルのままです。
ドキュメントにもあるけど、Next.js (v13) を使って開発をしているときに サードパーティのライブラリだったり typekit だったり css<link> タグを使って読み込ませるときは next/document<Head> 内で読み込ませましょうってメモ

import Head from 'next/head';

export const SiteHead: FC = () => {
  return (
    <Head>
      <link rel="stylesheet" href="path/to/your/stylesheet.css" />
    </Head>
  );
};

head を共通化しようとして上記のように next/head<Head> 内に stylesheet の読み込みを書くと次のような警告が発生する
Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="https://use.typekit.net/mhd5rrk.css"). Use Document instead.

A <link rel="stylesheet"> tag was added using the next/head component.
We don't recommend this pattern because it will potentially break when used with Suspense and/or streaming. In these contexts, next/head tags aren't:

  • guaranteed to be included in the initial SSR response, so loading could be delayed until client-side rendering, regressing performance.
  • loaded in any particular order. The order that the app's Suspense boundaries resolve will determine the loading order of your stylesheets.

cf. No Stylesheets In Head Component | Next.js

英語ちからが無さすぎて翻訳しても良く分からなかったけど、ざっくりな理解だけど next/head<Head> 内に <link rel="stylesheet"> を追加すると

という事なんじゃないだろうか。

/src/pages/_document.tsx

import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html>
      <Head>
        <link rel="stylesheet" href="path/to/your/stylesheet.css" /> {/* ここで CSS を追加する */}
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

CSS に限らず static な meta 情報は next/document<Head> 内に書くほうがパフォーマンス良さそう。
<Head>next/documentnext/head と 2つ存在するので紛らわしい…
全然関係ないけど、英語ちから&エンジニアリングちからが無さすぎてドキュメント読んでも翻訳しても意味分からんってこと多くてつらい。。。何から勉強すればいいの!?

おわり₍ ᐢ. ̫ .ᐢ ₎


[参考]

今季観てるアニメ フリーレンしか無いので、面白い作品教えてください