🛣️

【Remix】meta機能備忘録

に公開

Remixのmeta機能とは

Remixには、各ルートコンポーネントでmetaデータを定義できる機能が備わっています。
この機能を使うことで、SEO対策に重要なmetaタグやtitleタグを動的に設定することができます。

基本的な使い方

import type { MetaFunction } from "@remix-run/node";

export const meta: MetaFunction = () => {
  return [
    { title: "ページタイトル" },
    { name: "description", content: "ページの説明文" },
    { property: "og:title", content: "OGPタイトル" },
    { property: "og:description", content: "OGPの説明文" },
  ];
};

データに基づいたメタ情報の設定

loaderから取得したデータを使って、動的にメタ情報を設定することもできます。

export const meta: MetaFunction<typeof loader> = ({ data }) => {
  return [
    { title: data.article.title },
    { name: "description", content: data.article.description },
    { property: "og:image", content: data.article.ogImage },
  ];
};

Remixでは、ネストされたルートのmetaがマージされます。親ルートで設定したmetaを子ルートで上書きすることも可能です

// 親ルート
export const meta: MetaFunction = () => {
  return [
    { title: "サイト名" },
    { name: "description", content: "デフォルトの説明" },
  ];
};
// 子ルート
export const meta: MetaFunction = () => {
  return [
    { title: "ページ名 | サイト名" }, // 上書き
  ];
};

発展的な使い方

metaデータのマージ

親ルートと子ルートの間でmetaデータをマージする際の説明をします。

export const meta: MetaFunction = ({ matches }) => {
  // 親ルートのメタデータを取得
  const parentMeta = matches.flatMap(match => match.meta ?? []);
  
  // titleを除外して親のメタデータをマージ
  const filteredParentMeta = parentMeta.filter(meta => !("title" in meta));
  
  return [
    ...filteredParentMeta,
    { title: "新しいタイトル" },
    { name: "description", content: "新しい説明" }
  ];
};

グローバルメタデータの設定

アプリケーション全体で共通のメタデータは、root.tsxで直接設定できます。

app/root.tsx
export default function App() {
  return (
    <html lang="ja">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <Scripts />
      </body>
    </html>
  );
}

JSON-LDの設定

JSON-LDも設定できます。

export const meta: MetaFunction = () => {
  return [
    {
      "script:ld+json": {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "記事タイトル",
        "author": {
          "@type": "Person",
          "name": "著者名"
        }
      }
    }
  ];
};

locationパラメータの活用

URLのクエリパラメータに基づいてmetaタグを動的に設定できます。

export const meta: MetaFunction = ({ location }) => {
  const searchQuery = new URLSearchParams(location.search).get("q");
  return [
    { title: `"${searchQuery}"の検索結果` }
  ];
};

エラーページのmeta設定

エラー発生時に適切なmetaタグを設定することも可能です。

export const meta: MetaFunction = ({ error }) => {
  return [
    { title: error ? "エラーが発生しました" : "通常のタイトル" },
    { name: "description", content: error ? "エラーページです" : "通常の説明文" }
  ];
};

Discussion