I am using Next.js 13 and using the generateMetaData function for dynamic metadata works for openGraph, but how to do it for Twitter meta tags?
export async function generateMetadata( {params, searchParams}: Props, parent?: ResolvingMetadata): Promise<Metadata> {
return {
openGraph: {
type: "website",
url: '',
title: '',
description: '',
image: '',
}
}
}
For instance, the HTML output needs to be:
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:url" content={url} />
<meta property="twitter:title" content={ogTitle} />
<meta property="twitter:description" content={ogDescription} />
<meta property="twitter:image" content={ogImage} />
2
Answers
You need to do something very similar for twitter:
Don’t forget that the recommended dimensions are 1200x630px.
More info here: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#twitter
Also if you end up having issues with the title / description being rendered but not the image, you might want to use this way to specify the information for the image:
Make Sure you are using this function in the page.js file of the page that you like to share , or write it in app.jsx if you are sharing your whole website and want media to be rendered , I have added tag generation for whatsapp as well.
To make sure if your metatags are working fine , you can view source of your page and then check if the tags / OG tags are there or not . To view source of your page press ( Ctrl + U ) on the page that you are going to share , or you can use this validatior for twitter to see if you have a valid card ,twitter validator , just paste your page url and see in logs if there is green text or red. green text means you are probably doing things the right way.