'Dynamically insert og:meta tags from backend

I'd like to add social media sharing to my React SPA without SSR.

So when you share a link with specific parameters to Facebook / Twitter etc. you get a custom image/description/heading...

I've found this guide which is solving the problem, but in the NodeJS app. https://code.tutsplus.com/tutorials/adding-social-sharing-in-a-nodejs-single-page-application--cms-25530

Is it possible to do in backend which is using PHP?



Solution 1:[1]

Before reading the article, I came to the same conclusion as the author of the linked article. Social media sites gather og:meta tags by reading the HTML directly using simple HTTP GET requests. It is very, very unlikely that this og:meta parser is executing the JavaScript on your site (and waiting for it to finish rendering) so any client-side approach (e.g. using react-helmet) is bound to fail.

It simply isn't possible to generate og:meta tags without sever-side rendering. The article you link confirms this--they use Express, a server framework, to render og:meta tags.

However, what I interpret your post as asking is a way to insert og:meta tags via the backend while still serving up a React SPA to users. That's totally possible and the article lays out a great framework you can replicate in PHP.

I assume your PHP backend has some code that is serving up your React SPA. The most straightforward solution is to simply modify that code to also return og:meta tags in the <head> based on what route was requested. It's that simple. You can use simple string replacement to insert the tags, although a PHP HTML templating engine would be more professional and maintainable (the linked article uses a templating engine as well).

Based on the article, you can also clean this solution up by modifying the router to:

  • Differentiate normal (human using a browser) requests vs. social media bot requests
  • Return an HTML page with your normal React SPA code for browsers
  • Return a barebones HTML page with og:meta tags for bots

This way your browser users don't get useless meta tags in their <head> and social media crawlers don't get useless <script> and <style> tags.

(Personally, since I'm lazy, I would serve up the same HTML to bots and users alike. I think the article's solution is clean but also a bit overkill.)

Solution 2:[2]

You can use the react-helmet library to add elements into the head tag.

To install it:

npm i react-helmet // using NPM, or
yarn add react-helmet // using Yarn, or
pnpm i react-helmet // using PNpm

To use it, add this in the JSX of each page:

<Helmet>
  <meta property="og:title" content="..." />
  {/* more tags here */}
</Helmet>

Hope this solution is what you're looking for.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent La
Solution 2