Svelte and SvelteKit 5 cheatsheet
Svelte and SvelteKit 5: SvelteKit
8 common Svelte and SvelteKit 5 tasks.
Create a page
Folders under src/routes are URLs. [slug] is a dynamic segment, so this serves /blog/hello.
src/routes/blog/[slug]/+page.svelte
Load data on the server
A +page.server.ts load function runs on the server, and its result is passed to the page as data.
// +page.server.ts
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ params, fetch }) => {
const res = await fetch(`/api/posts/${params.slug}`);
return { post: await res.json() };
};
Use the loaded data
Read the load function's result through the data prop.
<script lang="ts">
let { data } = $props();
</script>
<h1>{data.post.title}</h1>
Handle a form on the server
Form actions receive the submitted form data. The form works without JavaScript and can be enhanced with use:enhance.
// +page.server.ts
import { fail } from "@sveltejs/kit";
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const email = data.get("email");
if (!email) return fail(400, { error: "Email is required" });
return { success: true };
},
};
Create an API endpoint
A +server.ts file exports a function per HTTP method.
// src/routes/api/hello/+server.ts
import { json } from "@sveltejs/kit";
export function GET() {
return json({ message: "Hello" });
}
Read a private environment variable
Variables from $env/static/private can only be imported in server code.
import { DATABASE_URL } from "$env/static/private";
Redirect
Redirect from server code, for example when the user isn't signed in.
import { redirect } from "@sveltejs/kit";
throw redirect(303, "/login");
Share a layout
A +layout.svelte wraps every page below it and renders the page with children.
<!-- src/routes/+layout.svelte -->
<script lang="ts">
let { children } = $props();
</script>
<nav>...</nav>
{@render children()}