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.
2
Answers
Thanks to everyone who helped me with the above issue. This is the corrected code
In NextJS, some parts of the HTML are rendered on the client (e.g. Google Chrome) and some other parts are rendered on the frontend server. If the metadata consumers don’t see the metadata that you see on the client, then it’s possible that the following happened:
<Head>
require some client-side processing, then the frontend server will not return the data in it and will just return a minimal HTML that tells the client how to keep loading it until it reaches the intended state.<Head>
.<Head>
.This problem can be solved by fetching the data that’s needed for the
<Head>
in the server. That can be done using getStaticProps or using getServerSideProps.