Configuring OpenGraph on Dynamic Pages in Next.js v14
The tools used are:
- Next.js
- TypeScript
- Next-Image-Export-Optimizer
- LinkedIn Post Inspector
What is the Open Graph Protocol?
In short, it allows platforms like LinkedIn to read any web page metadata and turn it into a rich object in a social graph. This allows the platforms to use this object as any other object on LinkedIn (OpenGraph). Next.js gives us the chance to set these tags in a couple different ways. Since we are using dynamic content, we will use the generateMetaData
approach (Next.js Docs).
Furthermore, since I do not have thousands of articles with different Images, I will be using different images for different articles on open graph.
Using Remote Images with Relative Paths
I am using the Next-Image-Export-Optimizer package to download and export images, and it has built in features where it downloads multiple versions of the image based on configuration. Since I already have this configured, I will use one of the smallest images generated for the open graph image.
The package parses the images as it begins to download them, and changes how they are saved during build time:
- It removes the protocol (https or http),
- it removes the file format (jpg),
- it changes the url forward slashes (/) to underscores (_),
- it stores the images under a different folder.
I created a simple function to parse sourceUrls coming in, and it returns a string with the file to use.
export const generateLocalImageUrl = (sourceUrl?: string): string => {
if (!sourceUrl) return '';
const generatedUrl = sourceUrl
.split('//')[1]
.split('.jpg')[0]
.split('/')
.join('_');
return `/optimized-images/${generatedUrl}-opt-384.webp`;
};
The Setup
export async function generateMetadata(
{ params }: MetaDataGeneratorProps,
parent: ResolvingMetadata
): Promise {
const slug = params['article-slug'];
const { data: articleData } = await getArticleData(slug);
const previousImages = (await parent)?.openGraph?.images || [];
const ftImageUrl =
generateLocalImageUrl(articleData.featuredImage.sourceUrl);
return {
metadataBase: new URL('https://pavelaparcana.com'),
title: articleData.title,
description:
articleData.metaDescription,
openGraph: {
images: [
ftImageUrl,
...previousImages
],
},
};
}
Note: metadataBase
is set to use relative paths. Read more over at the Next.js Docs
Once deployed, or if you have a staging environment, we can use the LinkedIn Post Inspector tool to see how our links show up in those platforms. Simply paste your production url or staging url, and LinkedIn will scan and try to display your open graph values.
Conclusion
In this article, we explored how to configure Open graph in Next.js with dynamic metadata using the generateMetaData approach. Depending on how you are serving images, you may have to tweak a few values and to use your images.