Sorry, no results found for "".

SvelteKit > SvelteKit + DatoCMS Overview

SvelteKit + DatoCMS Overview

Svelte is a frontend framework built around a simple idea: avoid the complexity of a Virtual DOM and compile components to responsive vanilla JS. SvelteKit is Svelte's full-stack framework: it sports file-based routing, API endpoints, and zero-configuration deployments on multiple providers (adapters for Vercel, Netlify and Cloudflare are provided and even used transparently for a great developer experience).

Svelte and SvelteKit together let you get started quickly with a set of sane defaults upon which you can build.

DatoCMS is the perfect companion to SvelteKit since it offers content, images and videos on a globally-distributed CDN. With this combo, you can have an infinitely scalable website, ready to handle prime-time TV traffic spikes at a fraction of the regular cost.

In the next paragraphs, will see how easy it is to combine Svelte with DatoCMS.

Fetching content from our GraphQL API

Svelte and SvelteKit invites developers to leverage existing standard APIs. fetch API is the conventional way of retrieving data from servers.

Let's start by installing @datocms/cda-client, a lightweight, TypeScript-ready package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS Content Delivery API:

Terminal window
npm install --save @datocms/cda-client

We can now create a function we can use in all of our components that need to fetch content from DatoCMS: Create a new directory called lib, and inside of it, add a file called datocms.js:

src/lib/datocms.js
import { env as privateEnv } from '$env/dynamic/private';
import { executeQuery } from '@datocms/cda-client';
export const performRequest = (query, options) => {
return executeQuery(query, {
...options,
token: privateEnv.PRIVATE_DATOCMS_CDA_TOKEN,
});
}

Make sure you set PRIVATE_DATOCMS_CDA_TOKEN as an actual API token of your DatoCMS project. You can create a new one under "Settings > API Tokens".

Loading data is achieved in SvelteKit by creating a +page.server.js file beside the +page.svelte component.

The load function exported from +page.js is called when the page is loaded. Here we can use our executeQuery function to load content from DatoCMS:

src/routes/+page.server.ts
const query = `
query HomeQuery {
blogPost { title }
}
`;
export const load = () => {
return executeQuery(query);
};

The data returned by the load function will be available to the page/layout component a data prop:

src/routes/+page.svelte
<script>
export let data;
</script>
<article>
<h1>{{ data.blogPost.title }}</h1>
</article>

You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.