Single Page Applications and Open Graph
Asked Answered
B

3

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.

Beggary answered 17/4, 2013 at 20:18 Comment(0)
L
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">

Lazos answered 17/4, 2013 at 21:13 Comment(3)
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.Beggary
@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.Telegraphic
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'.Sustain
L
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.

Laetitia answered 23/7, 2020 at 21:59 Comment(0)
D
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.

Dongola answered 17/9, 2021 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.