Go back to archives

Quick Start: Building a SvelteKit Project with Directus

SvelteKit logo

Welcome to my quick guide on how to create a functional SvelteKit project using Directus. I’ll also share some additional tips to start your project better.

What is SvelteKit?

SvelteKit is a popular Companion JavaScript Framework to Svelte.js - focusing on creating performant web applications. In this tutorial, you will learn how to build a website using Directus as a CMS. You will store, retrieve, and use global metadata such as the site title, create new pages dynamically based on Directus items, and build a blog.

Before you start programming:

You will need:

  • To install Node.js and a code editor on your computer.
  • A Directus project - follow my quickstart guide if you don't already have one. (Custom made)
  • Some knowledge of Svelte.

For starting a project in Svelte we firstly have to install Sveltekit. This can be done via:

bash
npm create svelte@latest your-project-name # Choose Skeleton project

Reminder: if you already have a folder open if you want to install it, you do not need to write your-project-name

Optimal if you use your-project-name - If you have used a new project folder you need to navigate to this folder using

bash
cd frontend

After that we have to install the node modules that we will be using. These are

bash
npm install
npm install @directus/sdk

Firstly, the .env file

To begin a project with an api we have to save this within an .env file. This file will not be pushed to Github. Make sure to create a .gitignore and ignore the files so they cannot be committed using:

bash
.env

Make sure the API URL is correct when initializing the Directus JavaScript SDK.

Second, the directus.js file

We now need to setup the Directus SDK and make it accessible globally. In order to make the best use of SvelteKit's Server Side Rendering, we will need to use SvelteKit's own fetch implementation. Create a new file named directus.js inside of the src/libs directory:

directus.js
js
import { createDirectus, rest } from '@directus/sdk';
import { readItems, readItem, updateItem, updateUser, createItem, deleteItem } from '@directus/sdk';
import { PUBLIC_APIURL } from '$env/static/public';

function getDirectusInstance(fetch) {
  	const options = fetch ? { globals: { fetch } } : {};
	const directus = createDirectus(PUBLIC_APIURL, options ).with(rest());
	return directus;
}

export default getDirectusInstance;

In order to make this work we also need to create a hooks.server.js file with the following content in the src directory. It makes sure that the required headers for fetching JavaScript content are returned by the SvelteKit Server.

hooks.server.js
js
export async function handle({ event, resolve }) {
	return await resolve(event, {
		filterSerializedResponseHeaders: (key, value) => {
			return key.toLowerCase() === 'content-type';
		},
	});
}

Theoretically you could also make HTTP requests to your Directus server endpoint directly via SvelteKit's fetch implementation. However the Directus SDK offers some nice additional features.

For this project I expect you have a default Directus build. For more information check out the quickstart.

Directus logo

Third, prepare SvelteKit to use Directus

Create a new page named +page.js within the folder /routes. This file's load function will be responsible to fetch the data on the client and on the server during Server Side Rendering.

+page.js
js
/** @type {import('./$types').PageLoad} */
import getDirectusInstance from '$lib/directus';
import { readItems } from '@directus/sdk';
export async function load({ fetch }) {
	const directus = getDirectusInstance(fetch);
	return {
		global: await directus.request(readItems('global')),
	};
}

Modify the +page.svelte file to use the new data and display it on our site:

+page.svelte
svelte
<script>
	/** @type {import('./$types').PageData} */
	export let data;
</script>

<h1>{data.global.title}</h1>
<p>{data.global.description}</p>

You can edit the global variables if you have set any. For examples is your api endpoint is "persons", you can show data.person.name in the +page.svelte

Now you have a working Svelte project with Directus!

Optional Features for Svelte Projects

In many projects, it's helpful to apply consistent styles across all pages, like setting a default background or text style. For this, I recommend adding a global.css file to your Svelte project.

  1. Inside the static folder, create a new directory called css.
  2. Add a file named global.css to it.
global.css
css
/*
    CSS text-wrap: balance property
    Allows multiple lines of text to have their lines broken in such a way that each line is roughly the same width, often used to make headlines more readable and visually appealing.

    https://caniuse.com/css-text-wrap-balance
 */
h1,
h2,
h3,
h4,
h5,
h6 {
    text-wrap: balance;
}


/*
    CSS max-width property
    In this case, we are setting the maximum width of the text to 65 characters, which is a good practice to make the text more readable and visually appealing.

    CSS property: text-wrap: pretty
    This property is used to break lines of text in a way that is visually appealing, often used to make paragraphs more readable and visually appealing.

    https://caniuse.com/mdn-css_properties_text-wrap_pretty
 */
p,
li,
figcaption {
    text-wrap: pretty;
    max-width: 65ch;
}

/*
    CSS property: container-type: inline-size
    This property is used to set the width of an element to the width of the containing block, often used to make elements fill the width of the container.

    https://caniuse.com/mdn-css_properties_container-type_inline-size
 */
body > :is(header, footer),
main,
section,
article {
    container-type: inline-size;
}

Why do this? I learned this technique from Kevin Powell. It optimizes text readability and improves project scalability, whether the project is small or large. Check out his explanation in this video.

Summary

In this guide, you’ve learned how to create a working SvelteKit project integrated with Directus as a CMS. We covered the following key steps:

  • Setting up SvelteKit and Directus, including project prerequisites.
  • Using the Directus SDK to connect to your Directus instance.
  • Fetching data from Directus and rendering it with SvelteKit.
  • Implementing global styles with a global.css file for better text readability and consistency across your site.

Thank You for Reading

Thank you for following along with this tutorial! I hope it helps you get started with SvelteKit and Directus. If you have any questions or feedback, feel free to reach out. Happy coding!

Like this blog? Click the button above to upvote it!