Effective SEO in SvelteKit

To make your SEO scalable in SvelteKit, you can create a reusable SEO component that automatically populates the meta tags based on the provided data. This way, you only need to specify the SEO-related information (like title, description, etc.) for each page, and the SEO component will handle the rest. Here's how you can achieve this:

Step 1: Create an SEO Component

Create a reusable SEO component inside the $lib directory that accepts the necessary data as props and renders the appropriate meta tags in the <svelte:head>.

<!-- src/lib/components/SEO.svelte -->
<script>
	import { page } from '$app/stores';

	const {
		title = 'My SvelteKit App',
		description = 'My SvelteKit App',
		image = 'https://example.com/image.jpg'
	} = $props();

	let url = $derived($page.url.href);
</script>

<svelte:head>
	<title>{title || defaultTitle}</title>
	<meta name="description" content={description} />
	<meta property="og:title" content={title} />
	<meta property="og:description" content={description} />
	<meta property="og:image" content={image} />
	<meta property="og:url" content={url} />
	<meta name="twitter:card" content="summary_large_image" />
	<meta name="twitter:title" content={title} />
	<meta name="twitter:description" content={description} />
	<meta name="twitter:image" content={image} />
</svelte:head>

Step 2: Use the SEO Component in Your Pages

In your individual pages or components, import the SEO component from $lib and pass the necessary data as props.

<!-- src/routes/about/+page.svelte -->
<script>
  import SEO from '$lib/components/SEO.svelte';

  const title = 'About Us -- Our Company';
  const description = 'Learn more about our company and mission.';
  const image = 'Image here';
</script>

<SEO {title} {description} />

<h1>{title}</h1>
<p>Welcome to our about page!</p>

In your <head> title use pipes | to use space. Your page's main target keyword should appear in the title tag, ideally towards the beginning. If you want to include your site or brand name, place it at the end of the title after a separator. The main keywords should come first.

Last updated