Reusable Metadata Factory
Factory function to generate consistent SEO metadata across all pages with Open Graph and canonical URLs.
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.
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.