Skip to content

Commit

Permalink
Include images in OG meta tags.
Browse files Browse the repository at this point in the history
  • Loading branch information
Lawrence Godfrey committed Dec 18, 2024
1 parent c75e815 commit e699fe4
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions server/controllers/articleController.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ const update = async (req, res, next) => {
const createMetaHtml = (article) => {
const description = article.content.substring(0, 160).replace(/[#*`_\[\]]/g, '') + '...';

// Extract the first image URL from the markdown content
const imageMatch = article.content.match(/!\[.*?\]\((.*?)\)/);
const imageUrl = imageMatch ? imageMatch[1] : null;

return `
<!DOCTYPE html>
<html>
Expand All @@ -74,13 +78,16 @@ const createMetaHtml = (article) => {
<meta property="og:type" content="article" />
<meta property="og:url" content="https://lawrences.tech/articles/${article._id}" />
<meta property="article:published_time" content="${article.createdAt.toISOString()}" />
${imageUrl ? `<meta property="og:image" content="${imageUrl}" />` : ''}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="${escape(article.title)}" />
<meta name="twitter:description" content="${escape(description)}" />
${imageUrl ? `<meta name="twitter:image" content="${imageUrl}" />` : ''}
</head>
<body>
<h1>${escape(article.title)}</h1>
<p>${escape(description)}</p>
${imageUrl ? `<img src="${imageUrl}" alt="${escape(article.title)}" />` : ''}
</body>
</html>
`;
Expand Down

0 comments on commit e699fe4

Please sign in to comment.