
- Svelte - Home
- Svelte - Introduction
- Svelte - Installation
- Svelte - Reactivity
- Svelte - Props
- Svelte - Logic
- Svelte - Events
- Svelte - Bindings
- Svelte - Classes
- Svelte - Styles
- Svelte - Actions
- Svelte - Transitions
- Svelte - Advance Reactivity
- Svelte - Reusing Content
- Svelte - Motion
- Svelte - Advanced Binding
- Svelte - Advanced Transitions
- Svelte - Context API
- Svelte - Special Elements
- SvelteKit Basics
- SvelteKit - Introduction
- SvelteKit - Routing
- SvelteKit - Loading Data
- SvelteKit - Headers
- SvelteKit - Cookies
- SvelteKit - Shared Modules
- SvelteKit - Forms
- SvelteKit - API Routes
- SvelteKit - States
- SvelteKit - Errors
- SvelteKit - Redirects
- SvelteKit Advanced
- SvelteKit - Hooks
- SvelteKit - Page Options
- SvelteKit - Link Options
- SvelteKit - Advanced Routing
- SvelteKit - Advanced Loading
- SvelteKit - Environment Variables
- Svelte Resources
- svelte - Useful Resources
- svelte - Discussion
Sveltekit - Cookies
In SvelteKit, cookies are important for handling user sessions and preferences allowing an application to store small pieces of data on the user's browser, such as login information or user settings. In this chapter, we are going to learn about cookies and how to set and read them in Sveltekit.
What are Cookies?
Cookies are small pieces of data that are stored on the user's browser. They help remember information about the user, such as preferences or login status, and manage user data.
Reading Cookies
In SvelteKit, you can read a cookie by using the cookies.get(name, options)method within a load function. You can read cookies in SvelteKit in the following format:
export function load({ cookies }) { const cookieValue = cookies.get('cookie-name'); return { cookieValue }; }
Setting Cookies
In SvelteKit, you can set a cookie by using the cookies.set(name, value, options) method inside a load function. For setting cookies, it is important to provide a path where the cookies are accessible. Setting cookies in SvelteKit can be done in the following format:
export function load({ cookies }) { cookies.set('cookie-name', 'cookie-value', { path: '/', httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24 // 1 day }); }
Security Defaults
SvelteKit, automatically applies some key security settings to cookies to enhance protection such as:
- httpOnly: true makes sure that cookies can't be accessed by JavaScript, which helps lower the risk of attacks like Cross-Site Scripting (XSS).
- secure: true means that cookies are only sent over HTTPS connections, which helps keep them safe from being intercepted while they are being sent.
- sameSite: 'lax' helps in protecting against Cross-Site Request Forgery (CSRF) attacks by managing when cookies are sent with requests from other sites.
Example
The code in +server.js manages both GET and POST requests to read and write cookies. Meanwhile, the Svelte component in +page.svelte retrieves the current greeting from the server and automatically sets it when the component loads.
<!--src/routes/+server.js--> export const POST = async ({ cookies }) => { // Set a cookie named 'greeting' cookies.set('greeting', 'Hello from SvelteKit!', { path: '/' }); return new Response(JSON.stringify({ success: true }), { headers: { 'Content-Type': 'application/json' }, }); }; export const GET = async ({ cookies }) => { // Read the 'greeting' cookie or default to 'World' const greeting = cookies.get('greeting') || 'World'; return new Response(JSON.stringify({ greeting }), { headers: { 'Content-Type': 'application/json' }, }); }; <!-- src/routes/+page.svelte --> <script> let greeting = 'World'; // Default greeting const fetchGreeting = async () => { const response = await fetch('/?GET'); const data = await response.json(); greeting = data.greeting; }; const setGreeting = async () => { await fetch('/?POST', { method: 'POST' }); fetchGreeting(); // Refresh the greeting after setting the cookie }; // Fetch greeting when component mounts import { onMount } from 'svelte'; onMount(() => { fetchGreeting(); setGreeting(); // Set cookie on mount }); </script> <h1>Hello {greeting}!</h1>
Output
