Next.js Headコンポーネント完全ガイド:業務で使える実装パターン集

React / Next.js

Next.js Headコンポーネント完全ガイド:業務で使える実装パターン集

簡易的な解説

Next.jsのHeadコンポーネントは、ページの<head>タグ内にメタタグやタイトル、スクリプトなどを動的に挿入するための機能です。従来のHTML開発では<head>セクションは静的でしたが、Next.jsではコンポーネントの状態に応じて柔軟に制御できます。

特にSPA(Single Page Application)では、ページ遷移時にメタタグを適切に更新する必要があります。Next.jsのHeadコンポーネントを使うことで、各ページまたは各ルートで個別にメタタグを管理できます。

Next.js 13以降では、next/headに加えてnext/imageMetadata APIなどが登場し、メタタグ管理の方法が複数存在します。実務では、プロジェクトのバージョンと要件に応じて使い分けることが重要です。

業務でのユースケース

ユースケース1:ECサイトの商品ページ

ECサイトでは、商品ごとに異なるメタディスクリプション、OGP画像、構造化データを設定する必要があります。

ユースケース2:ブログシステムの記事管理

ブログの各記事には、タイトル、説明、著者情報、公開日時などのメタタグが必要です。これらは記事内容から動的に生成されます。

ユースケース3:多言語対応サイト

複数言語対応のサイトでは、言語ごとにメタタグを変更し、hreflang属性で検索エンジンに言語情報を伝える必要があります。

ユースケース4:SNS共有時の表示制御

TwitterやFacebookで記事を共有する際、適切なOGPタグを設定することで、プレビュー表示を最適化できます。

実装コード

基本的なHead使用例

// pages/products/[id].tsx
import Head from 'next/head';
import { GetStaticProps, GetStaticPaths } from 'next';

interface ProductPageProps {
  product: {
    id: string;
    name: string;
    description: string;
    image: string;
    price: number;
  };
}

export default function ProductPage({ product }: ProductPageProps) {
  const canonicalUrl = `https://example.com/products/${product.id}`;
  const ogImageUrl = `https://example.com${product.image}`;

  return (
    <>
      
        {product.name} | 商品 - 例店
        
        
        
        
        
        
        
        
        
        
        
      

      

{product.name}

{product.name}

{product.description}

¥{product.price.toLocaleString()}

); } export const getStaticPaths: GetStaticPaths = async () => { // 商品一覧を取得 const products = await fetch('https://api.example.com/products') .then(res => res.json()); return { paths: products.map((product) => ({ params: { id: product.id }, })), fallback: 'blocking', }; }; export const getStaticProps: GetStaticProps = async ({ params }) => { const product = await fetch( `https://api.example.com/products/${params?.id}` ).then(res => res.json()); return { props: { product }, revalidate: 3600, }; };

構造化データ(JSON-LD)の実装

検索エンジンがサイト内容を正確に理解するために、構造化データの実装が重要です。

// components/StructuredData.tsx
import Head from 'next/head';

interface StructuredDataProps {
  type: 'Product' | 'Article' | 'Organization';
  data: Record;
}

export function StructuredData({ type, data }: StructuredDataProps) {
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': type,
    ...data,
  };

  return (
    
      


















    


  

  

    
  

    
タイトルとURLをコピーしました