Introduction
When we encounter a link in a social media post we expect it to have an image preview, title and description like the ones shown below, right? We are less likely to click if there is no preview. I will explain how social media websites know what to display and how to make sure that links to your website will be displayed correctly.
OpenGraph and Meta Tags
Social Media websites use the [OpenGraph (og) protocol](https://ogp.me) to get information about your web page. This information has to be set with 'Meta Tags'. The easiest way to implement this in FastHTML is by adding `Socials` to your headers:
from fasthtml.common import *
hdrs = (
*Socials(title="My Website", description="This is my website", site_name='example.com',
twitter_site='@example', image='https://example.com/card_thumbnail.png',
url='https://example.com')
)
app, rt = fast_app(hdrs=hdrs)
@rt("/")
def get():
return Title("Home"), Div(H1("Welcome to FastHTML"))
serve()
Another option is to set meta tags yourself with `Meta` in [FastHTML](https://fastht.ml). For example:
meta_tags = [
# OpenGraph tags
Meta(property="og:title", content="Home - Personal website of Carlo Lepelaars"),
Meta(property="og:description", content="Personal website of Carlo Lepelaars..."),
Meta(property="og:image", content="https://carlo.ai/c.jpg"),
Meta(property="og:type", content="website"),
Meta(property="og:url", content="https://carlo.ai"),
# X/Twitter specific tags
Meta(name="twitter:site", content="@CarloLepelaars"),
Meta(name="twitter:creator", content="@CarloLepelaars"),
Meta(name="twitter:card", content="summary"),
Meta(name="twitter:title", content="Home - Personal website of Carlo Lepelaars"),
Meta(name="twitter:description", content="Personal website of Carlo Lepelaars..."),
Meta(name="twitter:image", content="https://carlo.ai/c.jpg"),
]
`og:` are OpenGraph tags. The `twitter:` tags are specific for optimizing [X.com](https://x.com) posts. The tags should be returned within a FastHTML route. Here is a basic example of a FastHTML route with meta tags:
from fasthtml.common import *
app, rt = fast_app(hdrs=None)
@rt("/")
def get():
return Title("Home"), *meta_tags, Div(H1("This is my website"))
serve()
This is sufficient to let social media websites know what to display. To verify this you can use [Social Share Preview](https://socialsharepreview.com), which will also give you suggestions on tags and image optimization.
That's it! Hope you learned something new and can easily integrate OpenGraph into your website.