Solved Facebook share issue with React

mohit thakur
1 min readSep 24, 2020

Recently I came across a requirement which needed me to share my webpage to Facebook.

I was amazed to see that Single page applications cannot share correctly because the Facebook crawlers don't wait until JavaScript updates the meta tags.

What were my choices?

  • Pr-render my application which is expensive , you can check yourself :D
  • Use Nextjs for server side rendering and again learn the whole framework, No way I just learned react (just kidding don't tell my recruiters)

So i wasted 2 days and these arguments could not move me?

So I came up with my own solution. Why not use the weakness of not running JavaScript to our advantage.

In 2 simple steps you can share your webpage without much of hassle

  • Step 1

Create an api which just serves meta tags which means only html doc with head and required meta tags.

<!DOCTYPE html>
<head>
<meta property="og:url" content="http:examsonline.asia" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Exams Online" />
<meta property="og:description"
content="Create Online Exams"/>
<meta property="og:image" content="http://test.examsonline.asia/logo-lg.png"/>
</head>
<script>
setTimeout(()=>{
window.location.href ="www.examsonline.asia"
},500)
</script>
</html>

Step 2

look at this section of the api, once the user goes this page rendered by the api he will be redirected to the actual page your wanted to share.

<script>
setTimeout(()=>{
window.location.href ="www.examsonline.asia"
},500)
</script>
</html>

This script tag adds the script to redirect user to correct page.

So we have taken advantage of the javascript not run by crawlers to overcome the sharing issue in single page applications.

You can checkout live implementation at Examsonline

--

--