Lesson 4 of 8 advanced 6 min read

Advanced Options

Progressive Web Apps with $app/manifest and $app/env, form state preservation with snapshot, and CSP.

Interactive Laboratory

Live Runtime

Experiment directly with Advanced Options concepts in real time

SvelteKit Full-Stack Pipeline
1. Request
Hook
2. Loader
load()
3. Server
SSR HTML
4. Browser
Hydrate

Advanced Options: Service Workers, Snapshots, and Security

Explore powerful enterprise capabilities for offline support, UI state preservation across back/forward navigation, and Content Security Policy (CSP).


1. Built-in Service Worker Support ($app/manifest & $app/env)

Create src/service-worker.ts and SvelteKit will bundle and version it automatically:

// src/service-worker.ts
/// <reference types="@sveltejs/kit" />
import { version } from '$app/env';
import { build, files } from '$app/manifest';
 
const CACHE_NAME = `cache-${version}`;
const ASSETS = [...build, ...files];
 
self.addEventListener('install', (event: any) => {
	event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)));
});

2. Preserving Form State with snapshot

When users navigate away and click “Back”, prevent loss of unsaved textarea input or scroll offsets:

<!-- src/routes/comments/+page.svelte -->
<script lang="ts">
	import type { Snapshot } from './$types';
 
	let commentText = $state('');
 
	export const snapshot: Snapshot<string> = {
		capture: () => commentText,
		restore: (value) => {
			commentText = value;
		}
	};
</script>
 
<textarea bind:value={commentText} placeholder="Write a draft comment..."></textarea>

3. Content Security Policy (CSP)

Configure strict nonces and CSP directives in svelte.config.js:

// svelte.config.js
export default {
	kit: {
		csp: {
			mode: 'auto',
			directives: {
				'script-src': ['self']
			}
		}
	}
};