0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js App Router での Prefetch の挙動を理解する

Posted at

はじめに

Next.js の機能の1つとして、ページを Prefetch してくれる仕組みがあります。

この記事では、簡単なサンプルを作成し、Prefetch がどのように動作しているのかを見てみます🙋‍♂️

実装概要

src/
  app/
    prefetch/
      page-1/
        page.tsx
      page-2/
        page.tsx
      page-3/
        page.tsx
  middleware.ts
  • Page1 → 次ページ(Page2)へのリンクを表示
  • Page2 → 次ページ(Page3)へのリンクを表示
  • Page3 → 最後のページ。
  • middleware → リクエストをログ出力して挙動を確認

Prefetch が行われるタイミング

Link コンポーネントは、「リンクが画面に表示された時」Prefetch を行います。

なお、公式ドキュメントにある通り、 「プリフェッチは production でのみ有効」 です。

Prefetching is only enabled in production.

つまり、開発環境(npm run dev) では Prefetch が行われません。

実際の挙動を確認するには、npm run buildnpm run start の手順で本番相当の環境でテストを行う必要があります。

サンプルコード

検証用のサンプルコードを作成します。

src/app/prefetch/page-1/page.tsx

import Link from 'next/link';

export default function Page1() {
  return (
    <div>
      <h1>Page 1</h1>
      <Link href="/prefetch/page-2">
        Go to Page 2 (Prefetched)
      </Link>
    </div>
  );
}

src/app/prefetch/page-2/page.tsx

import Link from 'next/link';

export default function Page2() {
  return (
    <div>
      <h1>Page 2</h1>
      <Link href="/prefetch/page-3">Go to Page 3</Link>
    </div>
  );
}

src/app/prefetch/page-3/page.tsx

export default function Page3() {
  return (
    <div>
      <h1>Page 3</h1>
    </div>
  );
}

src/middleware.ts

import { NextResponse, NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  console.log('リクエスト詳細:', {
    url: request.url,
    pathname: request.nextUrl.pathname,
    method: request.method,
    headers: Object.fromEntries(request.headers),
  });

  return NextResponse.next();
}

実際のリクエストログを見てみる

1. 本番相当でサーバーを起動する

npm run build
npm run start

2. リクエストログの確認

Page1 を開いた直後に、ビューポートに Link が表示されるため、Next.js は自動で Page2 のページデータを取りにいきます。

↓ コンソールからリクエストの結果を確認することができます。

リクエスト詳細: {
  url: 'http://localhost:3000/prefetch/page-1',
  pathname: '/prefetch/page-1',
  method: 'GET',
    headers: {
    ...
  }

...

リクエスト詳細: {
  url: 'http://localhost:3000/prefetch/page-2',
  pathname: '/prefetch/page-2',
  method: 'GET',
  headers: {
    ...
  }
}

まとめ

本番環境でしか実行されない点は注意が必要ですね!
本記事が誰かの役に立てたのであれば嬉しいです👌

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?