'Dynamically add meta tags to index.html for shared link previews

I have an angular page that displays rich content (PDF, images, videos, etc). I need to create a shareable link to that HTML page with the right metatags so the correct title and description are displayed on rich link previews (when other services like Facebook, twitter, SMS, etc. display it). The shareable link has all the data needed encoded in it for my project to fetch the HTML page content. How can I add the correct metatags to the index.html page of my angular project dynamically so that the shareable link preview appears correctly on other services?

Example of how I want the link preview to appear when shared on other platforms: https://i.stack.imgur.com/ZRJ8X.png

Solution 1:[1]

For meta tags to work, they must be on the HTML page of the link before any javascript is run. Some platforms may run some javascript on the external site when generating a link preview, but in general, meta tags must be on the html page before angular boots up, so client side code on the given page will not work for this purpose.

For my purposes, I have found the most effective way to accomplish this effect is to serve shareable links separately from the angular project, as HTML redirects.

For example, you can have your shareable links actually link to your API, and have the API pass the data along when redirecting. Instead of example.com/article?id=2&exampleParam=123, you'd have api.example.com/share?id=2&exampleParam=123. The /share API endpoint would return an HTML file with the correct meta tags on it, along with a meta tag that will redirect to your app: <meta http-equiv="refresh" content="0; URL='https://example.com/article?id=2&shareableParam=123'" />

You just need to have your shareable link lead to an HTML page that has the correct meta tags, with a redirect to the actual URL on your app. There isn't any easier way to do this as far as I am aware, given that the meta tags must be present before angular is run. Server-side rendered angular projects are a totally different game, though, but I assume most people running into this issue will be using clientside rendering only.


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 Paul