kobweb
kobweb copied to clipboard
Render meta tags server side
In order to get dynamic embeds on Discord, Slack, Twitter etc, it is necessary to directly imbed opengraph meta tags into the html that is being served. Trivial for fully static pages, but pages with dynamic content (most likely dynamic routes in kobweb terms) need to have these meta tags replaced server side.
Below is a working example using Ktor and very basic SSR/templating.
// app
LaunchedEffect(Unit) {
if (AppGlobals.isExporting) {
document.title = "%{title}"
document.querySelector("""meta[name="og:title"]""")?.setAttribute("content", "%{title}")
document.querySelector("""meta[name="title"]""")?.setAttribute("content", "%{title}")
document.querySelector("""meta[name="description"]""")?.setAttribute("content", "%{description}")
document.querySelector("""meta[name="og:description"]""")?.setAttribute("content", "%{description}")
document.querySelector("""meta[name="og:image"]""")?.setAttribute("content", "%{image}")
document.querySelector("""meta[name="twitter:image"]""")?.setAttribute("content", "%{image}")
}
}
// server
get("/post/{postId}") {
call.respondText(
html.replace("%{title}", "Some username")
.replace("%{description}", "Posts description")
.replace("%{image}", "Url of authors avatar"),
ContentType.Text.Html)
}
Opposed to full SSR support, templating only meta tags is rather self-contained. It would only require a hook on the backend, which accepts the user's dynamic variables.