kobweb icon indicating copy to clipboard operation
kobweb copied to clipboard

Render meta tags server side

Open TheDome0 opened this issue 1 year ago • 0 comments

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.

TheDome0 avatar Apr 03 '25 19:04 TheDome0