CMS Development

VShvets
Member

Add dynamic meta tag depend on ?id with React CMS

Hi, my site has a list of posts with url /post?id=<id>. The posts are stored on a backend outside hubspot. I need to add meta tags with relevant information about the post based on the ID. I am using https://github.hubspot.com/cms-react/ and everything works fine except one thing. When I use getServerSideProps to get the post data and useInlineHeadAsset() to add a meta tag, the meta tag is added in the form of

 

 

 

<script nonce=‘hs-random-nonce’>
document.head.innerHTML += `<meta property=‘og:image’ content=‘url’/>;`;
</script>

 

 

 

My code looks like this.

 

 

 

export const getServerSideProps = withUrlAndQuery(async (props, url) => {
  const id = url.url.searchParams.get('id');
  const post = await fetch(...);

  return {
    serverSideProps: {
      img: post.img
    },
    caching: {
      cacheControl: {
        maxAge: 60
      }
    }
  }
});
 
export const  Component = ({ serverSideProps }) => {
  const img = serverSideProps.img;
  
  useInlineHeadAsset(() => {
    return <>
      <meta property="og:image" content={img} />
    </>
  });

 

 

 

I was testing and noticed that the meta tag is added to the head if I don't use getServerSideProps, but in that case I can't get the post data.

 

Is there any solution to this problem or is there any other way to dynamically add meta tag?

0 Upvotes
1 Reply 1
kennedyp
Community Manager
Community Manager

Add dynamic meta tag depend on ?id with React CMS

Hi @VShvets! Welcome to the Community-- happy to have you here 😊

 

I understand you are looking for a way to dynamically set a meta tag on your blog pages based on the post ID. Thank you for including your code. I'd like to invite some of our experts to see if they have come across this type of request! @Kevin-C, @albertsg, @Indra do any of you have insight into retrieving the post data and dynamically adding a meta tag? Thanks in advance!

 

Best, 
Kennedy


Did you know that the Community is available in other languages?
Join regional conversations by changing your language settings !
0 Upvotes