Tutorial Fetching content from Newt CMS in SvelteKit
In this article I wanted to cover how to fetch content from a headless CMS like Newt, and display the content in SvelteKit.
First we will decide structure for the content.
We will create a model named Article for our - well - articles.
Create the route for articles in SvelteKit:
Simply create a new folder inside src/routes. We will name the new folder articles.
Then we will create a new file named [id].svelte inside the articles folder.
I know, it's a strange file name, but that's how routing works in SvelteKit.
Then we will edit the file we just created:
[id].svelte
<script context="module">
import { createClient } from 'newt-client-js';
/** @type {import('./__types/[id]').Load} */
export async function load({ params, fetch, session, stuff }) {
const client = createClient({
spaceUid: 'YOUR_SPACE_ID',
token: 'YOUR_API_TOKEN',
apiType: 'cdn' // You can specify "cdn" or "api".
});
// get a content
const article = await client.getFirstContent({
appUid: 'YOUR_APP_ID',
modelUid: 'article',
query: {
slug: params.id
}
})
if (article) {
return {
status: 200,
props: {
article
}
};
}
return {
status: 404
};
}
</script>
<script>
export let article;
</script>
<div>
<h1>{article.title}</h1>
</div>
And that's it! We now have access to the article data, and we can display the data on the page. Here we get to see how easy it is to fetch content from a headless CMS with SvelteKit.