sveltesveltekitmeta-tagssanity

Add meta tags to dynamic page in sveltekit


I have a blog built with Sveltekit an Sanity, the meta tags for the main page works, but when I try to use meta tags in my dynamic pages, they dont show up. I have tried svelte:head and even the svelte-meta-tags library

My route is sitename/post/[slug]

Here is my dynamic page:

<script lang="ts">
    import { PortableText } from '@portabletext/svelte';
    import { formatDate } from '$lib/utils';
    import { urlFor } from '$lib/utils/image';
    import type { PageData } from './$types';

    import SvelteSeo from 'svelte-seo';

    import { page } from '$app/stores';

    export let data: PageData;

    console.log('data', $page);
    console.log(data);
    
</script>
<SvelteSeo
    title={$page.data.title}
    description={$page.data.excerpt}
    canonical={`site.com/post/${$page.data.slug.current}`}
    openGraph={{
        url: `site.com/post/${$page.data.slug.current}`,
        title: $page.data.title,
        description: $page.data.excerpt,
        images: $page.data.mainImage ? [{ url: urlFor($page.data.mainImage).url() }] : [],
        site_name: 'Site'
    }}
    twitter={{
        title: $page.data.title,
        description: $page.data.excerpt,

        image: $page.data.mainImage ? urlFor($page.data.mainImage).url() : undefined
    }}
    keywords={$page.data.tags ?? [].join(', ')}
/>

<section>
...
</section>

Please help


Solution

  • Try wrapping your SEO component inside a {#key} block. https://svelte.dev/docs/logic-blocks#key For a simple explanation, this directive is used to efficiently update DOM elements.

    {#key $page.pathname.url}
       <SvelteSeo.../>
    {/key}