From 94cae8d04adb3aaabcd2944db11cf474c987872f Mon Sep 17 00:00:00 2001 From: John SJ Anderson Date: Thu, 31 Oct 2024 12:01:46 -0700 Subject: [PATCH] Add OpenGraph and other metadata to blog posts [#134] --- static-site/app/blog/[id]/page.tsx | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/static-site/app/blog/[id]/page.tsx b/static-site/app/blog/[id]/page.tsx index 3b0807526..bb8e77262 100644 --- a/static-site/app/blog/[id]/page.tsx +++ b/static-site/app/blog/[id]/page.tsx @@ -1,7 +1,14 @@ +import { Metadata } from "next"; import { redirect } from "next/navigation"; import React from "react"; import { BigSpacer } from "../../../components/spacers"; +import { + siteLogo, + siteTitle, + siteTitleAlt, + siteUrl, +} from "../../../data/BaseConfig"; import { getBlogPosts, markdownToHtml } from "../utils"; @@ -20,6 +27,48 @@ export function generateStaticParams(): BlogPostParams[] { }); } +// generate opengraph and other metadata tags +export async function generateMetadata({ + params, +}: { + params: BlogPostParams; +}): Promise { + const { id } = params; + + // set up some defaults that are independent of the specific blog post + const baseUrl = new URL(siteUrl); + const metadata: Metadata = { + metadataBase: baseUrl, + openGraph: { + description: siteTitleAlt, + images: [ + { + url: `${siteUrl}${siteLogo}`, + }, + ], + siteName: siteTitle, + title: siteTitle, + type: "website", + url: baseUrl, + }, + }; + + // this is the specific post we're rendering + const blogPost = getBlogPosts().find((post) => post.blogUrlName === id); + + if (blogPost) { + const description = `Nextstrain blog post from ${blogPost.date}; author(s): ${blogPost.author}`; + + metadata.title = blogPost.title; + metadata.description = description; + metadata.openGraph!.description = description; + metadata.openGraph!.title = `${siteTitle}: ${blogPost.title}`; + metadata.openGraph!.url = `/blog/${blogPost.blogUrlName}`; + } + + return metadata; +} + export default async function BlogPost({ params, }: {