Search code examples
javascripthtmlsveltesveltekitsupabase

Dynamic social sharing cards populated in <svelte:head>


I've built a blog website and am trying to implement dynamic social share cards for each individual blog. While everything appears to be working properly when I inspect the head element in developer tools, when I do a live test or run the link through social sharing preview tools (such as OpenGraph) my dynamic store variables are undefined.

I'm pulling the data from Supabase and saving it to a store. Here's the code that I'm using in my svelte:head tag:

<svelte:head>
    {#await $blogBeingViewed then blog}
        <title>Website - {blog.title}</title>
        <meta name="title" content="{blog.title}">
        <meta name="description" content="{blog.subtitle}">

        <!-- Open Graph / Facebook -->
        <meta property="og:type" content="website">
        <meta property="og:url" content="https://www.website.com/article/{blog.id}">
        <meta property="og:title" content="{blog.title}">
        <meta property="og:description" content="{blog.subtitle}">
        <meta property="og:image" content="{blog.image_url}">

        <!-- Twitter -->
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:url" content="https://www.website.com/article/{blog.id}">
        <meta name="twitter:title" content="{blog.title}">
        <meta name="twitter:description" content="{blog.subtitle}">
        <meta name="twitter:image" content="{blog.image_url}">
    {/await}
</svelte:head>

Any ideas why I'm experiencing this failure to properly populate my meta tags when attempting to share on social media?

I hope that I'm using the proper terminology (I'm just a hobbyist). Feel free to ask any follow-up questions that would help me to clarify my question.

Thank you for your time and assistance.

I've tried multiple variations on the code block shown above, i.e. without "#await," using "#if," etc.


Solution

  • After sleeping on it, I realized that I needed to move my database logic from onMount to a +page.ts file. Data fetching done in an onMount function is not rendered on the server. By moving this logic to +page.ts, the data is fetched on the server and available when the page renders in the browser.