{comment.content}
{/each} {:catch error}Error: {error.message}
{/await} ``` ## Rerunning Load Functions Load functions rerun when: - Referenced `params` or `url` properties change - Parent load function reruns (if using `await parent()`) - Manually invalidated with `invalidate()` or `invalidateAll()` ### Manual Invalidation ```js /** @type {import('./$types').PageLoad} */ export async function load({ fetch, depends }) { depends('app:random'); const response = await fetch('https://api.example.com/random-number'); return { number: await response.json() }; } ``` ```svelte ``` ## Using getRequestEvent Access request event in shared server code: ```js // src/lib/server/auth.js import { redirect } from '@sveltejs/kit'; import { getRequestEvent } from '$app/server'; export function requireLogin() { const { locals, url } = getRequestEvent(); if (!locals.user) { redirect(307, `/login?${new URLSearchParams({ redirectTo: url.pathname + url.search })}`); } return locals.user; } ``` ## docs/kit/20-core-concepts/30-form-actions.md # Svelte Form Actions ## Default Actions Define a default action in `+page.server.js`: ```js /// file: src/routes/login/+page.server.js export const actions = { default: async (event) => { // TODO log the user in } }; ``` Use it with a simple form: ```svelte ``` Target actions from other pages: ```html ``` ## Named Actions Multiple actions in one page: ```js export const actions = { login: async (event) => { // TODO log the user in }, register: async (event) => { // TODO register the user } }; ``` Invoke with query parameter: ```svelte ``` ## Action Anatomy Actions receive a `RequestEvent` and can return data: ```js import * as db from '$lib/server/db'; export const actions = { login: async ({ cookies, request }) => { const data = await request.formData(); const email = data.get('email'); const password = data.get('password'); const user = await db.getUser(email); cookies.set('sessionid', await db.createSession(user), { path: '/' }); return { success: true }; } }; ``` Access returned data in the page: ```svelte {#if form?.success}Successfully logged in! Welcome back, {data.user.name}
{/if} ``` ### Validation Errors Return validation errors with the `fail` function: ```js import { fail } from '@sveltejs/kit'; export const actions = { login: async ({ cookies, request }) => { const data = await request.formData(); const email = data.get('email'); const password = data.get('password'); if (!email) { return fail(400, { email, missing: true }); } const user = await db.getUser(email); if (!user || user.password !== db.hash(password)) { return fail(400, { email, incorrect: true }); } // Success case } }; ``` Display errors in the form: ```svelte ``` ### Redirects Redirect after an action: ```js import { fail, redirect } from '@sveltejs/kit'; export const actions = { login: async ({ cookies, request, url }) => { // Authentication logic if (url.searchParams.has('redirectTo')) { redirect(303, url.searchParams.get('redirectTo')); } return { success: true }; } }; ``` ## Loading Data After an action runs, the page's `load` functions run again. Update `event.locals` when setting cookies: ```js // In action event.cookies.delete('sessionid', { path: '/' }); event.locals.user = null; ``` ## Progressive Enhancement ### use:enhance Basic enhancement: ```svelte ``` To target actions in `+page.server.js` explicitly: ```js const response = await fetch(this.action, { method: 'POST', body: data, headers: { 'x-sveltekit-action': 'true' } }); ``` ## GET vs POST For non-data-modifying forms, use `method="GET"`: ```html ``` This navigates to `/search?q=...` using client-side routing without invoking an action. ## docs/kit/20-core-concepts/40-page-options.md # Svelte 5 Page Options ## Core Concepts ### Rendering Modes SvelteKit supports three rendering strategies: - **Server-Side Rendering (SSR)**: Default mode - renders on server first, then hydrates in browser - **Client-Side Rendering (CSR)**: Interactive components rendered in browser - **Prerendering**: Generate static HTML at build time Options can be set in `+page.js`, `+page.server.js`, `+layout.js`, or `+layout.server.js`. Child layouts/pages override parent settings. ## Page Options ### prerender ```js // Static generation at build time export const prerender = true; // Enable prerendering for this route export const prerender = false; // Disable prerendering export const prerender = 'auto'; // Prerender but keep in SSR manifest ``` **Notes:** - Prerendering crawls your app starting from the root - Routes with `prerender = true` are excluded from SSR manifests - For fully static sites, use `adapter-static` - During prerendering, `building` from `$app/environment` is `true` **When not to prerender:** - When users need different content (authentication, personalization) - Pages with form actions - Pages that access `url.searchParams` during prerendering **Route conflicts:** - Use file extensions for server routes (`foo.json` instead of `foo`) - Pages are written as `foo/index.html` instead of `foo` ### entries For dynamic routes that should be prerendered: ```js // src/routes/blog/[slug]/+page.server.js export function entries() { return [ { slug: 'hello-world' }, { slug: 'another-blog-post' } ]; } export const prerender = true; ``` Can be async to fetch data from CMS/database. ### ssr ```js export const ssr = false; // Disable server-side rendering ``` Renders empty shell page instead of full HTML. Useful for browser-only code but generally not recommended. ### csr ```js export const csr = false; // Disable client-side rendering ``` When disabled: - No JavaScript is sent to client - Page works with HTML/CSS only - No form progressive enhancement - Links cause full-page navigation - HMR is disabled For development-only CSR: ```js import { dev } from '$app/environment'; export const csr = dev; ``` ### trailingSlash ```js export const trailingSlash = 'never'; // Default - redirects /about/ to /about export const trailingSlash = 'always'; // Redirects /about to /about/ export const trailingSlash = 'ignore'; // Treats both forms as valid ``` Affects prerendering output: `always` creates `about/index.html`, otherwise creates `about.html`. ### config Platform-specific configuration for adapters: ```js /** @type {import('some-adapter').Config} */ export const config = { runtime: 'edge' }; ``` Config objects merge at top level but not deeper levels. ## docs/kit/20-core-concepts/50-state-management.md # Svelte 5 State Management ## Server State Guidelines ### Avoid Shared State on Server Servers are stateless and shared by multiple users. Never store user data in shared variables: ```js // NEVER DO THIS - shared variable exposes data between users let user; export function load() { return { user }; } export const actions = { default: async ({ request }) => { const data = await request.formData(); user = { name: data.get('name') }; // BAD: shared between users } } ``` Instead, authenticate users with cookies and store data in databases. ### No Side-Effects in Load Load functions should be pure: ```js // NEVER DO THIS - modifies global state import { user } from '$lib/user'; export async function load({ fetch }) { const response = await fetch('/api/user'); user.set(await response.json()); // BAD: affects all users } ``` Instead, return the data: ```js export async function load({ fetch }) { const response = await fetch('/api/user'); return { user: await response.json() }; } ``` ## Using Context for State Use Svelte's context API for component-scoped state: ```svelte ``` ```svelteWelcome {user().name}
``` ## Component State Preservation Components are reused during navigation. Reactive values must be properly declared: ```svelte ``` Correct approach: ```svelte ``` To force component remounting on navigation: ```svelte {#key page.url.pathname}Status: %sveltekit.status%
Message: %sveltekit.error.message%
``` ## Type Safety Customize error shape in TypeScript: ```ts declare global { namespace App { interface Error { code: string; id: string; } } } export {}; ``` ## docs/kit/30-advanced/30-link-options.md # SvelteKit Link Options ## Navigation Basics SvelteKit uses standard `` elements for navigation between routes. When clicking a link within your app, SvelteKit: - Imports the code for the new page - Calls necessary `load` functions - Updates the UI without a full page reload ## data-sveltekit-preload-data Controls when data loading begins: ```html