13

I'm writing a SPA that uses underscore templating. The app searches for and rates music albums and returns the result via ajax. If facebook open graph metatags cannot be altered dynamically and the url of the page is constant regardless of search result, how can i make it so users can share that they rated a certain album.

ie)

<meta property="fb:app_id"      content="118454308341351" /> 
<meta property="og:url"         content="http://www.appurl.com" /> 
<meta property="og:title"       content="Fleetwood Mac's Rumors" /> 
<meta property="og:image"       content="AppImg.jpg" /> 

and update those properties to reflect a given search result.

AesopWaits
  • 171
  • 2
  • 8

3 Answers3

5

The way I handle this is to create a dynamic page which I use as my open graph object, which is simply populated from the url parameters and redirects back to my SPA using the meta redirect.

<meta http-equiv="refresh" content="0;URL=http://YOUR_WEBSITE_WITH_DYNAMIC_CONTENT">

Joe T
  • 794
  • 4
  • 6
  • 2
    Solved this by creating a separate OpenGraph controller which would be pointed to by the FB.api call to rates. The controller returns an html page with OG meta tags that are populated from a model consisting of the title, image, etc. – AesopWaits Apr 18 '13 at 14:26
  • 2
    @AesopWaits, would you care to share that solution? I’m running into the problem of needing different OG tags for different “pages” running on a SPA. – Martin Adams May 20 '17 at 18:09
  • Tried this but facebook also followed the redirect so I went with redirecting from the backend link to the frontend link in the server when user agent didn't start with 'facebookexternalhit'. – Kris Feb 12 '21 at 20:41
3

Thanks to this tutorial I found a solution: https://speakerdeck.com/sienatime/facebook-sharing-for-single-page-apps?slide=15

I send only meta tags if the user-agent of the http request includes "facebookexternalhit".

Here is some code for a backend with node and express:

app.get('/', (req,res) => {
  if(req.header('user-agent').includes('facebookexternalhit'){
    res.send(`
      <meta property="og:title" content="The Slits' Cut" />
    `);
  } else {
    res.sendFile(index.html);
  }  
})

You could also write your own middleware for that.

dyedwiper
  • 151
  • 12
0

Our solution was to use Netlify pre-rendering, which pre-renders and then caches the rendered HTML to serve to crawlers and bots specifically.

This seems to work well. It allows us to dynamically update the OG meta tags, which are then cached by Netlify and served to crawlers, so they see the correct content.

It was easy to setup too, so if you are using Netlify this may be a good solution for you.

Adam Reis
  • 4,165
  • 1
  • 44
  • 35