typescriptbeginner

Reusable Metadata Factory

Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.

typescript
import type { Metadata } from 'next';

const BASE_URL = 'https://example.com';
const SITE_NAME = 'My App';

interface MetaInput {
  title: string;
  description: string;
  path: string;
  image?: string;
  noIndex?: boolean;
}

export function createMetadata({
  title,
  description,
  path,
  image,
  noIndex,
}: MetaInput): Metadata {
  const url = `${BASE_URL}${path}`;
  const ogImage = image ?? `${BASE_URL}/api/og?title=${encodeURIComponent(title)}`;

  return {
    title: `${title} — ${SITE_NAME}`,
    description,
    alternates: { canonical: url },
    openGraph: {
      title,
      description,
      url,
      siteName: SITE_NAME,
      images: [{ url: ogImage, width: 1200, height: 630 }],
      type: 'website',
    },
    twitter: {
      card: 'summary_large_image',
      title,
      description,
      images: [ogImage],
    },
    robots: noIndex ? { index: false, follow: false } : undefined,
  };
}

// Usage in page:
// export function generateMetadata({ params }) {
//   return createMetadata({
//     title: 'My Page',
//     description: 'Page description',
//     path: `/page/${params.slug}`,
//   });
// }

Use Cases

  • Consistent page SEO
  • Dynamic meta generation
  • Open Graph previews

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.