Svelte Kit

Introduction

  • SvelteKit is a framework for rapidly developing robust, performant web applications using Svelte. If you're coming from React, SvelteKit is similar to Next.

Data Pre-rendering

  • SvelteKit allows server-side rendering, but also can be disabled to let application be single app application (spa)

+page.ts
import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';

/** @type {import('./$types').PageLoad} */
export const load:PageLoad = ({ params }) => {
	if (params.slug === 'hello-world') {
		return {
			title: 'Hello world!',
			content: 'Welcome to our blog. Lorem ipsum dolor sit amet...'
		};
	}

	throw error(404, 'Not found');
}

// Disable SSR
// export const csr = true;
// export const ssr = false;
+page.svelte
<script>
    export let data: ApiKeysPage;
</script>
<div>
    {data.title}
</div>

API

  • The page can act as an api

login/+page.server.js
/** @type {import('./$types').Actions} */
export const actions = {
	login: async (event) => {
		// TODO log the user in
	},
	register: async (event) => {
		// TODO register the user
	}
};
login/+page.svelte
<form method="POST" action="?/register">

Hook

  • 'Hooks' are app-wide functions you declare that SvelteKit will call in response to specific events, giving you fine-grained control over the framework's behaviour

  • Every time the SvelteKit server receives a request — whether that happens while the app is running, or during prerendering — and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
	if (event.url.pathname.startsWith('/custom')) {
		return new Response('custom response');
	}

	const response = await resolve(event);
	return response;
}
  • Allows you to modify (or replace) a fetch request that happens inside a load or action function that runs on the server

/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
	if (request.url.startsWith('https://api.yourapp.com/')) {
		// clone the original request, but change the URL
		request = new Request(
			request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
			request
		);
	}

	return fetch(request);
}

Last updated

Was this helpful?