Svelte/SvelteKit > Integrate DatoCMS with Svelte

Integrate DatoCMS with Svelte

Building an application using Svelte and GraphQL is a quick way to go live with a CMS-backed website.

With the globally-distributed CDN serving the Content Delivery API of DatoCMS, you can serve content directly to your end users without an intermediate server. You maintain and host a static front-end application; we deal with the rest!

See also: Integrating DatoCMS with SvelteKit. SvelteKit is a full-stack framework for Svelte.

Fetching content from our GraphQL API

There are multiple options to fetch GraphQL content from DatoCMS with Svelte.

  • If you want to start simple, follow Svelte's suggestion and leverage the standard web API: fetch API is the conventional way of retrieving server-side data, and it's well supported by browsers;

  • If you need something ready-made, head down to Houdini, a complete GraphQL solution for Svelte applications.

We also have a Houdini-based example project in our marketplace.

Quick start using fetch

Use the standard fetch function to retrieve data from the DatoCMS GraphQL Content Delivery API in a Svelte component.

<script>
import { onMount } from 'svelte';
const query = gql`
query {
blogPost {
title
}
}
`;
let data = null;
onMount(async () => {
const response = await fetch('https://graphql.datocms.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: "Bearer YOUR_API_TOKEN",
},
body: JSON.stringify({ query })
})
const json = await response.json()
data = json.data;
});
</script>
<article>
{#if data}
<h1>{{ data.blogPost.title }}</h1>
{/if}
</article>sv

Make sure you replace YOUR_API_TOKEN with an actual API token of your DatoCMS project. You can create a new one under "Settings > API Tokens".

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