What is SvelteKit's approach to authentication?
Answer
SvelteKit authentication typically uses cookies and server hooks. Pattern: 1. Login action: verify credentials in a form action, set a session cookie: cookies.set('session', token, { path: '/', httpOnly: true, secure: true, sameSite: 'strict', maxAge: 3600 }). 2. Server hook: validate the session cookie on every request and set the user in event.locals: export async function handle({ event, resolve }) { const session = event.cookies.get('session'); event.locals.user = session ? await validateSession(session) : null; return resolve(event); }. 3. Load function: access locals.user in server load functions, redirect unauthenticated users. 4. Page layout: pass user to all pages via layout load function. Popular libraries: Auth.js (formerly NextAuth) has a SvelteKit adapter, Lucia is a lightweight auth library built for SvelteKit. JWT-based stateless auth is also common — store the JWT in an HttpOnly cookie.
More Svelte / SvelteKit Questions
View all →- Intermediate What are Svelte custom stores and the store contract?
- Intermediate How does SSR (Server-Side Rendering) work in SvelteKit?
- Intermediate What are SvelteKit adapters?
- Intermediate What is the difference between prerendering, SSR, and CSR in SvelteKit?
- Intermediate How do you manage environment variables in SvelteKit?