Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Attachments
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

The setHeaders function can’t be used with the Set-Cookie header. Instead, you should use the cookies API.

In your load functions, you can read a cookie with cookies.get(name, options):

src/routes/+page.server
export function load({ cookies }) {
	const visited = cookies.get('visited');

	return {
		visited: visited === 'true'
	};
}

To set a cookie, use cookies.set(name, value, options). SvelteKit defaults the path to /, making the cookie available throughout your app.

src/routes/+page.server
export function load({ cookies }) {
	const visited = cookies.get('visited');

	cookies.set('visited', 'true');

	return {
		visited: visited === 'true'
	};
}

Now, if you reload the iframe, Hello stranger! becomes Hello friend!.

Calling cookies.set(name, ...) causes a Set-Cookie header to be written, but it also updates the internal map of cookies, meaning any subsequent calls to cookies.get(name) during the same request will return the updated value. Under the hood, the cookies API uses the popular cookie package — the options passed to cookies.get and cookies.set loosely follows its Cookie object. SvelteKit sets the following defaults to make your cookies more secure:

{
	httpOnly: true,
	secure: true,
	sameSite: 'lax',
	path: '/'
}

Edit this page on GitHub

1
2
3
4
5
<script>
	let { data } = $props();
</script>
 
<h1>Hello {data.visited ? 'friend' : 'stranger'}!</h1>