Skip to content
← Back to rules

nextjs/no-before-interactive-script-outside-document 正しさ

何をするか

pages/_document.js の外で next/scriptbeforeInteractive 策略を使用することを禁止します。
このルールにより、beforeInteractive ロード戦略を使用するスクリプトは、その効果が最大となるドキュメントコンポーネント内でのみ使用されることが保証されます。

なぜ問題なのか

beforeInteractive 策略は、ページのハイドレーション(再構築)が開始する前にスクリプトを読み込むように設計されています。これは、pages/_document.js 内に配置された場合にのみ確実に正しく動作します。それ以外の場所で使用すると:

  • 意図した早期読み込み動作が得られない可能性がある
  • スクリプトの読み込みタイミングが不安定になる
  • ハイドレーション不一致やその他の実行時問題が発生する可能性がある
  • アプリケーションのパフォーマンス最適化に悪影響を及ぼす可能性がある

このルールに対して誤りなコードの例:

jsx
// pages/index.js
import Script from "next/script";

export default function HomePage() {
  return (
    <div>
      <Script
        src="https://example.com/script.js"
        strategy="beforeInteractive" // ❌ 間違った配置
      />
    </div>
  );
}

このルールに対して正しいコードの例:

jsx
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head />
        <body>
          <Script
            src="https://example.com/script.js"
            strategy="beforeInteractive" // ✅ 正しい配置
          />
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

使い方

このルールを 有効化 するには、設定ファイルまたは CLI で次のように使用できます:

json
{
  "plugins": ["nextjs"],
  "rules": {
    "nextjs/no-before-interactive-script-outside-document": "error"
  }
}
bash
oxlint --deny nextjs/no-before-interactive-script-outside-document --nextjs-plugin

参照