SvelteKit SEO

Search Engine Optimization (SEO) in SvelteKit is easier than on any other JavaScript framework I have worked with. I will discuss how to do it in this article.

svelte logo

Want to build a Svelte/SvelteKit site? Hire Me.

Why SEO is Easy in SvelteKit?

I appreciate how the svelte:head tag was introduced to resolve almost all meta tag issues in SvelteKit. By placing meta tags inside these tags, they are directed to the head part of your HTML document, and it undergoes Server-Side Rendering.

I had struggled considerably to achieve this in NEXT and NUXT. SvelteKit provides the simplest and easiest solution of all. Let’s explore some essential meta tags.

Canonical Tag

Your website may be available on the web through different URLs. Here is an example:

https://example.com/example
https://www.example.com/example
https://example.com/example/
https://example.com/example/index.html

Now, a bot will consider all these as distinct pages, and one or more of these pages may be penalized for duplicated content.

However, you can inform the bot - as it crawls through these pages - using a tag to specify which page is the original.

<link rel="canonical" href="https://www.example.com" />

Now, let’s see how to implement this in SvelteKit.

First, we need to obtain the pathname of the page.

+layout.server.js

export const load = async ({ url }) => {
    return {
        pathname: url.pathname
    };
}

Now, we can create our tag.

+layout.svelte

<script>
  export let data;
  const { pathname } = data;
</script>

<!-- the usual tag in layout files -->
<slot/>

<!-- canonical meta tag -->
<svelte:head>
  {#key pathname}
    <link rel="canonical" href="{SITE_URL}{pathname}" />
  {/key}
</svelte:head>

I added the key here for safety because sometimes the tag may not update as the URL changes.

TO BE CONTINUED…

Find related articles

Let's discuss on Twitter