How to Add JSON-LD to a SvelteKit App

· 386 words · 2 minute read

In modern web development, JSON-LD (JavaScript Object Notation for Linked Data) is a popular method for adding structured data to a website, especially if you want a better SEO. If you’re using SvelteKit, adding JSON-LD can be tricky. I spent a few hours looking for the right solution. I share it here so you don’t have to!


About JSON-LD 🔗

JSON-LD is a lightweight Linked Data format designed to make web data easy to share and understand. Its primary use is in SEO, where it provides structured data for search engines to generate rich snippets in search results. Examples include product ratings, event information, and FAQ schema.


Step-by-Step Guide to Add JSON-LD in a SvelteKit App 🔗

Step 1: Plan Your Structured Data 🔗

Before you dive into coding, decide the type of structured data you need. Use Google’s Schema.org Documentation for reference. Here are common use cases:

  • BlogPost: For articles or blogs.
  • FAQPage: For FAQs.
  • Product: For e-commerce.

Step 2: Add JSON-LD in SvelteKit 🔗

In SvelteKit, you typically add JSON-LD directly into the <svelte:head> of your app’s pages for better SEO. Here’s how:

  1. Open your SvelteKit route file
  2. Use the <script> tag to inject JSON-LD in the <svelte:head>.
  3. As you’ll put all the data in a JSON object and call this object in the HTML code we’ll need to use the @html tag. That will generate the HTML directly, with our object
  4. You can add to your single file, or, even better, create a SEO compoment and call it on every page where you need the JSON-LD

Here is the code:

<script>

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    "headline": 'How to Add JSON-LD to SvelteKit',
    "author": {
      "@type": "Person",
      "name": 'John Doe'
    },
    "datePublished": '2024-12-01',
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": 'https://example.com/blog/how-to-add-json-ld',
    }
  };
</script>

<svelte:head>
  {@html `<script type="application/ld+json">${JSON.stringify(jsonLd)}</script>`}
</svelte:head>

<article>
</article>

Best Practices for JSON-LD in SvelteKit 🔗

  • Keep It Lightweight: Avoid unnecessary attributes to keep your JSON-LD concise.
  • Focus on Accuracy: Ensure your data aligns with your page content.
  • Test Frequently: Validate each implementation to prevent schema errors.
  • Dynamic Handling: Use dynamic JSON-LD for large-scale applications to reduce maintenance.

Conclusion 🔗

This little snipper could help you to enhance your website’s SEO. If you see some improvements after a few weeks or if you have any questions send me a message on bluesky or twitter