Svelte and SvelteKit invites developers to leverage existing standard APIs. fetch
API is the conventional way of retrieving data from servers.
Loading data is achieved in SvelteKit by creating a +page.js
file beside the +page.svelte
component:
The load
function exported from +page.js
is called when the page is loaded, and the returned data are made available to the page via conventional props.
// src/routes/[slug]/+page.js// PUBLIC_DATOCMS_TOKEN is set using environment variables or via `.env` file.import { PUBLIC_DATOCMS_TOKEN } from "$env/static/public";const QUERY = `query Post($slug: String) {post(filter: {slug: {eq: $slug}}) {title}}`;export async function load({ fetch, params }) {const { slug } = paramsconst response = await fetch('https://graphql.datocms.com', {method: 'POST',headers: {Authorization: `Bearer ${PUBLIC_DATOCMS_TOKEN}`,},body: JSON.stringify({query: QUERY,variables: { slug }}),});const { data } = await response.json();return { data };};
The QUERY
is the GraphQL query, and of course it depends on the models available in your specific DatoCMS project. You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.
Inside the load
function, you can use JS to work on the data received from DatoCMS and pass it down to your component. You could actually use any kind of HTTP client: you're not tied to GraphQL at all.
Finally create the Svelte component that will be rendered when the page is requested:
<!-- src/routes/[slug]/+page.svelte --><script>export let data;$: ({ data: { post } } = data);</script><h1>{post.title}</h1>
Here you are, with a simple website retrieving content from DatoCMS via GraphQL and showing it in a HTML page.
SvelteKit has first class support for Typescript or JSDoc comments: unless your project is really basic, consider jumping to the magical world of typed Javascript dialects. Other DatoCMS libraries you may need also include type definitions.
Once you understood the principles of Svelte and SvelteKit, it's a good idea to evaluate a complete library, like the well integrated Houdini.
You can see that in the previous example we used an environment variable starting with PUBLIC_
so that it can be embedded into the bundle.
To create the API token for a DatoCMS project, go to the "Settings > API Tokens" section, making sure you only give it permission to access the (read-only) Content Delivery API.
Then, create a .env
file in your SvelteKit project that look something like this:
PUBLIC_DATOCMS_TOKEN=THE_TOKEN_YOU_JUST_CREATED
Once that's done, you are able to import the token anywhere in your project with the following statement:
import { PUBLIC_DATOCMS_TOKEN } from "$env/static/public";