I added some dynamic meta tags for a page in my next.js application.
import CoinTossPage from '@/views/CoinTossPage';
import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import axios from 'axios';
function CoinTossComponent() {
const router = useRouter();
const { id } = router.query;
const [poolData, setPoolData] = useState(null);
useEffect(() => {
if (id) {
fetchPoolData();
}
}, [id]);
// fetch pool data from API using pool id
const fetchPoolData = async () => {
try {
let config = {
method: 'get',
url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
headers: {
Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
},
};
const response = await axios(config);
if (response.status === 200) {
const payload = response.data.payload;
if (payload) {
setPoolData(payload);
} else {
setPoolData(null);
}
}
} catch (error) {
console.log('ERROR while fetching active pools from API ', error);
}
};
return (
<>
<Head>
<meta property="og:title" content={poolData?.tokenSymbol} />
<meta property="og:image" content={poolData?.imageUrl} />
</Head>
<CoinTossPage />
</>
);
}
export default CoinTossComponent;
This is how it is added and, this is how it appear when I look it on page inspect.
It's clearly showing the dynamic content in meta tags. But when I share the page link, this image is not appearing.
What is the issue?
I tried reading their documentation https://nextjs.org/learn/seo/rendering-and-ranking/metadata and added meta tags according to it.
Thanks to everyone who helped me with the above issue. This is the corrected code
import CoinTossPage from '@/views/CoinTossPage';
import React from 'react';
import Head from 'next/head';
import axios from 'axios';
function CoinTossComponent({poolData}) {
return (
<>
<Head>
<meta property="og:title" content={poolData?.tokenSymbol} />
<meta property="og:image" content={poolData?.imageUrl} />
</Head>
<CoinTossPage />
</>
);
}
export async function getServerSideProps(context) {
const { id } = context.query; // Access the route parameter
let config = {
method: 'get',
url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
headers: {
Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
},
};
const response = await axios(config);
const poolData = response.data.payload;
// Return the data as props
return {
props: {
poolData,
},
};
}
export default CoinTossComponent;