👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Connect your content to SvelteKit

Assuming you've followed along with the previous steps of configuring schema and editing content, you should be all set up for the next step of bringing your content to the world. Since your content is ultimately just data available through APIs, there’s practically no limit to where you can put it! It doesn’t even have to be the Web, as long as the system can send an HTTP request and do something with the returned JSON data.

In this guide, you will add the necessary code to a SvelteKit starter to pull in your content from your Sanity Content Lake. Below, you’ll find a simple boilerplate as an embedded CodeSandbox project. If you open it in a new window and start editing, it will fork and be tied to your account if you log in. You can also download the code and run it locally or import it to your GitHub account. To see the finished code, you’ll find another CodeSandbox embed at the end of this guide.

Follow on CodeSandbox or locally

SvelteKit requires a server, so this is a CodeSandbox Container. These sandboxes can only be forked if you are logged in. To follow along, we recommend you either log in to CodeSandbox, or create an account if you don't have one. Alternatively, you can clone the project from GitHub to your local machine by using the following command:

git clone https://github.com/sanity-io/get-started-sanity-sveltekit.git

and then install the dependencies with

npm install.

What you need to know

This guide assumes that you have some prior knowledge of SvelteKit and Svelte. If you don’t, but want to learn it, then we recommend checking out the official Svelte tutorial and SvelteKit documentation. That being said, this guide has been written intentionally so as to keep the code as simple as possible, so you might be able to tag along here too.

Add a SvelteKit endpoint route

In addition to routes that are pages, SvelteKit has the concept of endpoint routes. Such routes are used to get data from somewhere and then use it in a page or component.

In this guide, we’ll create an index page that lists the number of pets that reside in our Sanity Content Lake. For this, we’ll build the index page itself and an endpoint route that accompanies it. For the endpoint route, we’ll use the @sanity/client package, which we’ll pass the data.

👉 Add the @sanity/client package by searching for it by name in CodeSandBox’s dependency box to the left of the code editor. Clicking it or pressing return will add it to the package.json as if you were running npm i @sanity/client locally.

👉 Then, under src/routes, create +page.js file and add this code:

// src/routes/+page.js

import {createClient} from "@sanity/client";

const client = createClient({
  projectId: "[ your project ID ]",
  dataset: "[ your preferred dataset, eg production ]",
  apiVersion: "2021-10-21",
  useCdn: false
});

First, we import the Sanity client and create a new instance of it and pass it some properties:

  • projectId: This is the unique identifier for your project that contains all your users, datasets, and other settings. You do not need to treat it like a secret. You’ll find the project ID in the sanity.json file in your studio or on the project page on sanity.io/manage.
  • apiVersion: Usually, you’d want to put in today’s date YYYY-MM-DD to get the newest version of the query API.

While you don’t have to configure the following properties, it can be useful to know about them:

  • dataset: This is a collection of documents within a project. You can have multiple datasets (for example staging and production).
  • useCdn: If you set this to true the client will fetch content from our cache delivery network. In this case, however, we will not generate a whole lot of API traffic, and we want updates to be instantly available, so set this to false

Querying for content

So far, our starter project only has a hardcoded list of pets. We want to change that and make the page display pets from our Content Lake.

👉 Within the endpoint route file (src/routes/+page.js), we export an async function that returns pets. Add the following lines to the end of the file:

// /src/routes/+page.js

import {createClient} from "@sanity/client";

const client = createClient({
  projectId: "[ your project ID ]",
  dataset: "production",
  apiVersion: "2021-10-21",
  useCdn: false
});

export async function load({ params }) {
  const data = await client.fetch(`*[_type == "pet"]`);

  if (data) {
    return {
      pets: data
    };
  }
  return {
    status: 500,
    body: new Error("Internal Server Error")
  };
}

Here's what's going on. In this new function, we call the fetch method that the Sanity client exposes and pass it a GROQ query. This GROQ query filters ([]) all (*) your documents down to those with pet as the value for _type. If it works, it will return an array of documents as objects to our index page.

👉 On the index page, pets will be available under data. Add the following to src/routes/+page.svelte, so that the pets become available in our template as pets.

<!-- /src/routes/+page.svelte -->
<script>
  export let data;
</script>

The display of pets happens in these lines of +page.svelte, which should work now that you have set up the fetch function and passed the data into the template.

{#if pets && pets.length}
<ul>
  {#each pets as pet}
	<li>{pet.name}</li>
  {/each}
</ul>
{:else}
	<p>No pets found.</p>
{/if}

We then use the following lines to display the data that is returned, for your reference.

{#if pets && pets.length}
<pre>
{JSON.stringify(pets, null, 2)}
</pre>
{:else}
<p>Your data will show up here when you've configured everything correctly</p>
{/if}

Adding your URL to the Cross-Origins Resource Sharing (CORS) settings

In this example, SvelteKit will run the code inside of endpoint route on the server (or in a serverless function if you have deployed it to production) and generate a JSON file with the data. In this case, there will be no requests to your Sanity Content Lake from the browser at all.

Browsers come with security that prevents code injection that steals information from your cookies and passes them to third parties. This is called CORS. To allow your CodeSandbox site to get content from your project, you need to add its URL to your project’s CORS origins settings.

👉 First, grab the URL from the preview pane in your Codesandbox, it should look something like this https://RANDOM_LETTERS.csb.app/.

👉 Then head over to the API tab in your project settings at sanity.io/manage. A little bit down the page you'll find the section named "CORS Origins". Click the button labeled "Add CORS Origin", paste the URL from Codesandbox into the URL field, and hit save (you don’t need to “Allow credentials”). That’s it!

Continue to the next step or view the finished CodeSandbox below.

Next steps →

Was this article helpful?