1
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)でメタデータを生成する方法について書いていきます。

参考

静的メタデータの設定方法

静的メタデータを設定するには、以下のように書きます。
「metadata」関数をエクスポートする形で定義し、その中で、静的なメタデータを定義できます。

/app/blog/page.tsx
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "タイトル",
  description: "説明",
};

動的メタデータの設定方法

例として、ブログの詳細ページなどで、ブログのタイトルをメタデータに設定したい場合などがあります。
その時は、以下のようにすると、動的にメタデータを設定できます。

/app/blog/[blogId]/page.tsx
import { Metadata } from "next";

export const generateMetadata = async ({ params }: { params: { blogId: string } }): Promise<Metadata> => {
 // ブログの詳細データを取得する関数
  const blogData: ArticleContent = await blodDetailData(params.blogId);

  return {
    title: blogData.title,
    description: blogData.title
  };
}

このように、「generateMetadata」関数をエクスポートする形で定義、その中でデータの取得、メタデータの設定を行うことができます。

Faviconを設定

最後に、Faviconを設定する方法です。
いくつか方法があるみたいですが、今回は「icon.tsx」を設置する方法について書いていきます。
まず、ルートディレクトリにある「page.tsx」と同じ階層に「icon.tsx」を設定し、以下のようにソースを書いていきます。

〇設定する項目

  • runtime
    ランタイム(実行中にコードで使用できるライブラリ、API、および一般的な機能)を設定
  • size
    画像のサイズを設定
  • contentType
    画像の形式を設定
  • Iconメソッド
    ICONを生成するメソッド
/app/icon.tsx
import { ImageResponse } from 'next/og'
 
// Route segment config
export const runtime = 'edge'
 
// Image metadata
export const size = {
  width: 32,
  height: 32,
}
export const contentType = 'image/png'
 
// Image generation
export default function Icon() {
  return new ImageResponse(
    (
      // ImageResponse JSX element
      <div
        style={{
          fontSize: 24,
          background: 'black',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'white',
        }}
      >
        A
      </div>
    ),
    // ImageResponse options
    {
      // For convenience, we can re-use the exported icons size metadata
      // config to also set the ImageResponse's width and height.
      ...size,
    }
  )
}

以下の記事に、主な実装例が書いてあります。

最後に

他にも色々な記事を書いているので、よければ読んでいってください!

1
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
1
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?