CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software // CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software

Understanding sveltekit load functions

Cover for Understanding sveltekit load functions

Abstract

A SvelteKit page is defined by the content in its +page.svelte file, along with any +layout.svelte files that surround it. But before these Svelte files get rendered, data can be provided by load functions. In this article we further explore SvelteKit load functions and how to use them.

Basic usage

In our project's file structure, a +page.svelte file can have an associated +page.js file next to it.

Sveltekit folder structure

Image: Sveltekit folder structure

Imagine we want a webpage that uses data from the load function to show a title. Such scenario would look as follows.

The +page.svelte file:

// XML //

The +page.js file:

// JAVASCRIPT //

When the following structure gets rendered without any additional layout files, it becomes the following HTML:

// XML //

This load function runs on both the server and client, during the initial server load and on further clientside page hydration. If your particular use case requires it to run only on the client or server (e.g. when you want it to read from the local filesystem) we have to look a bit further to the +page.server.js file.

Note

This article assumes typeless javascript files. All of the content also holds true for page.ts files or page.js files with JSDoc annotations.

Server only load function

As mentioned above, if we want our load function to run on the server only, a +page.server.js file is the solution. Common use cases are reading from the local filesystem or accessing an external API which requires reading environment variables.

// JAVASCRIPT //

In such case, our +page.svelte file would look identical as above.

Accessing the page slug

When we design our page to make use of a slug, we want to access that slug data in the load function as well.

Sveltekit folder structure with a slug

Image: Sveltekit folder structure with a slug

// JAVASCRIPT //

Our +page.svelte file would still look identical as in the first example.

Loading data in a layout file

In a similar fashion, data can also be loaded in a +layout.js file and used in a +layout.svelte file. Likewise if you require the load function to only happen serverside, a +layout.server.js file is the solution.