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)でメタデータを設定する

Last updated at Posted at 2025-01-30

環境

next: v14.2.3

設定方法

Next.js(App Router)では、メタデータを設定する方法として静的および動的な設定方法が用意されている。
これら実装方法について、簡単な例を交えて残す。

1. 静的な設定(オブジェクトmetadata

Pageファイル、またはRoot Layoutファイルにて、オブジェクトmetadataをエクスポートすることで、簡単に静的なメタデータを設定可能。
下記例は、ページのタイトルを設定している。

page.tsx
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Qiita',
};

export default function Page() {
  return (
    // 省略
  );
}

2. 動的な設定(関数generateMetadata

動的な情報(現在のルートパラメータや外部情報、親セグメントのmetadataなど)を利用して、Metadataオブジェクトをエクスポートすることで、メタデータを動的に設定可能。
下記例は外部から取得したタイトルを設定している。

page.tsx
import type { Metadata } from 'next';

export async function generateMetadata(): Promise<Metadata> {
  const fetchedTitle = await fetch('https://...')
    .then((res) => res.json())
    .then((json: { title: string }) => json.title);

  return {
    title: fetchedTitle,
  };
}

export default function Page() {
  return (
    // 省略
  );
}

3. 実装時の注意

  • オブジェクトmetadata と関数generateMetadataサーバーコンポーネントのみサポートされている。
  • 一つのRoute Segmentでオブジェクトmetadata と関数generateMetadata を両方エクスポートできない。どちらか一方のみ実装する必要がある。

参考文献

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?