| | |

SvelteKit 11 🧡 RequestEvent, Cookies & Auth — Managing sessions with event.cookies, event.locals, route protection, and CSRF protection

⏱️ Estimated read: 6 min | |

In SvelteKit, the server-side lifecycle is managed through the RequestEvent object. This object acts as the bridge between an incoming HTTP request and your application’s logic. By providing unified access to headers, cookies, and request-local storage, SvelteKit allows you to handle authentication and session management in a consistent, predictable way.

Managing authentication in a stateless server environment requires careful handling of cookies and secure storage. The hooks.server.ts file serves as the central middleware layer where you validate sessions for every incoming request. By populating event.locals, you make user identity available across your entire application, from load functions to API endpoints.

This chapter covers how to utilize event.cookies for session persistence, how to populate event.locals for authenticated requests, and how to protect routes while ensuring your application remains safe from Cross-Site Request Forgery (CSRF).

Key point: The RequestEvent is the immutable handle for a single HTTP request; by using event.locals to attach authenticated user state within hooks.server.ts, you create a secure, request-scoped data flow that is accessible globally across your server-side logic.


Why RequestEvent and Cookies exist

The stateless web problem. HTTP is inherently stateless. Cookies exist to provide the “memory” needed to persist a user session across multiple requests, allowing the server to identify who is making a call.

The middleware requirement. Applications need a way to run logic (like auth checks) before any page or API route is reached. SvelteKit’s handle hook provides this interception point using the RequestEvent.

The Request-Local scope issue. Global variables in Node.js are shared across all users. event.locals provides an isolated bucket for each individual request, preventing data from leaking between User A and User B.

The CSRF vulnerability. Web browsers automatically include cookies with requests. Without CSRF protection, an attacker could trigger actions on behalf of a logged-in user. SvelteKit exists to abstract the complex security headers needed to prevent this.

The hydration necessity. SvelteKit must transfer server-side auth state to the client for the initial page load. The event.cookies API is designed to integrate perfectly with the serialization pipeline required for this transition.


a. The RequestEvent and locals

The RequestEvent is passed to every load function, API endpoint, and the handle hook. Its most powerful property is locals. Unlike global state, locals is specific to the current request and is reset the moment the request finishes.

// hooks.server.ts
export const handle = async ({ event, resolve }) => {
  // Populate locals before the route handler runs
  event.locals.user = { id: 1, role: 'admin' };

  return resolve(event);
};

By setting event.locals in hooks.server.ts, you make this object available everywhere. In any load function or +page.server.ts, you simply reference locals.user to determine if a user is authenticated.

b. Managing cookies

The event.cookies API provides a simple, unified way to read, set, and delete cookies. It handles the nuances of HTTP header formatting, making it trivial to manage session tokens securely.

// Setting a session cookie
event.cookies.set('session', token, {
  path: '/',
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  maxAge: 60 * 60 * 24 * 7 // 1 week
});

Always use httpOnly: true to prevent client-side scripts from stealing your tokens. The sameSite: 'strict' or 'lax' flags are crucial for preventing CSRF attacks by ensuring the cookie is not sent in cross-site requests.

c. Route protection and CSRF

Route protection should be centralized. By checking for the presence of event.locals.user inside your handle hook, you can redirect unauthorized users away from sensitive routes before they are ever rendered.

// hooks.server.ts
if (event.url.pathname.startsWith('/admin') && !event.locals.user) {
  throw redirect(303, '/login');
}

SvelteKit also provides built-in CSRF protection for POST, PUT, PATCH, and DELETE requests. SvelteKit verifies the origin header for form actions; if the origin doesn’t match your domain, the request is blocked, mitigating the primary vector for CSRF attacks.


Complete Example Session

// ============================================
// PART 1: HOOKS SETUP
// ============================================
// hooks.server.ts
export const handle = async ({ event, resolve }) => {
  const session = event.cookies.get('session');
  event.locals.user = session ? verify(session) : null;
  return resolve(event);
};

// ============================================
// PART 2: PROTECTED ROUTE
// ============================================
// +page.server.ts
export const load = ({ locals }) => {
  if (!locals.user) throw redirect(302, '/login');
  return { user: locals.user };
};

// ============================================
// PART 3: COOKIE MANAGEMENT
// ============================================
// login.ts
event.cookies.set('session', 'new-token', { httpOnly: true });

// ============================================
// PART 4: CSRF
// ============================================
// SvelteKit automatically blocks invalid form origins.

The example flow starts at the global handle hook, proceeds to page-specific protection, and handles cookies securely.


Quick Reference

Event Properties

PropertyPurpose
localsRequest-scoped storage
cookiesCookie CRUD interface
urlURL info for redirects
requestOriginal Request object

Cookie Options

FlagProtection
httpOnlyPrevents XSS access
secureForces HTTPS
sameSitePrevents CSRF

Best Practices

✅ Do This:

// Always set secure flags
event.cookies.set('id', val, { httpOnly: true, secure: true }); // ✅
// Check locals in load
if (!locals.user) throw redirect(303, '/login');               // ✅
// Clear cookies on logout
event.cookies.delete('session', { path: '/' });                // ✅

❌ Don’t Do This:

// Expose cookies to JS
event.cookies.set('id', val, { httpOnly: false });             // ❌
// Mutate global state in hooks
global.user = user;                                            // ❌
// Forget to set path on deletion
event.cookies.delete('session');                               // ❌

Common Pitfalls

PitfallWhy It HappensFix
LeakageStoring user in global variableUse event.locals
CSRF FailDisabled security headersLeave defaults enabled
XSS RiskhttpOnly: falseSet httpOnly: true
Redirect LoopAuth check on login pageExclude login route

Real-World Examples

1. Auth Hook

event.locals.user = await getUser(token);

2. Logout Action

event.cookies.delete('session', { path: '/' });

3. Route Guard

if (url.pathname.includes('/admin')) // ...

4. Cookie Validation

const token = event.cookies.get('session');

5. CSRF Protection

// Built-in to SvelteKit form actions

6. User Session Refresh

event.cookies.set('session', newToken, options);

7. Locals Injection

event.locals.theme = 'dark';

8. Redirect Helper

throw redirect(303, '/login');

9. Origin Check

// SvelteKit blocks unknown origins for actions

10. Server-side session

// Fetch from Redis based on cookie

Visual

The Request Lifecycle

┌──────────────────────────────────────────────┐
│  Request ──► hooks.server.ts (handle)        │
│    │                                         │
│    ├── Populate event.locals             │
│    └── Resolve Request ──► Page/API      │
│          │                               │
│          └── Route Protection Checks     │
└──────────────────────────────────────────────┘

Cookie Security

┌──────────────────────────────────────────────┐
│  Browser  ◄────►  Server (Set-Cookie)        │
│                     │                        │
│  Flags: HttpOnly, Secure, SameSite           │
│  Result: Immune to XSS & CSRF                │
└──────────────────────────────────────────────┘

Request Scoping

┌──────────────────────────────────────────────┐
│  Request A ──► event.locals (User A)         │
│  Request B ──► event.locals (User B)         │
│                                              │
│  Independent buckets, no interference.       │
└──────────────────────────────────────────────┘

Summary

ItemValue
EventRequestEvent
Storageevent.locals
Persistenceevent.cookies
SecurityhttpOnly, sameSite
Middlewarehooks.server.ts

Key takeaways:

  • event.locals is your workspace. It is the dedicated, request-safe container for user data, auth sessions, and temporary state.
  • Cookies require strict flags. Never create an auth cookie without httpOnly: true and secure: true.
  • Hooks are centralized. hooks.server.ts is the best place to perform global auth checks and redirect non-authenticated users.
  • CSRF is built-in. SvelteKit protects your form actions automatically; don’t fight it by disabling origin checks.
  • Stateless design. Keep your auth logic stateless by validating tokens from cookies on every single request rather than relying on server memory.

Remember: SvelteKit’s security model is designed around the idea that every request should be treated as an isolated, independent event. By properly leveraging RequestEvent and locals, you ensure that your authentication logic is bulletproof, portable, and immune to cross-user data corruption.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!