Svelte 68 🧡 Contextual Request Event Object — event.locals, event.cookies, event.fetch
The RequestEvent object is the foundational data structure in SvelteKit. It is the primary vehicle for communication between the server and your application’s logic. Whether you are working in a hooks.server.js file, a +page.server.js load function, or a form action, this object is passed as the first argument, containing the full context of the incoming HTTP request. It abstracts away the complexity of dealing with raw Request objects, providing a standardized interface for interacting with user state, session cookies, and network communication.
This chapter explores the three most critical properties of the RequestEvent: event.locals, which acts as the shared storage for the duration of a request; event.cookies, which handles the secure manipulation of cookies; and event.fetch, which provides a specialized fetch function tailored for server-side environments. Understanding these properties is essential for managing authentication, session state, and inter-service communication within a SvelteKit application.
Key point: The RequestEvent is a shared container passed into every request-processing function, providing unified access to user-specific data via locals, standardized cookie operations, and a specialized fetch client that preserves authentication context across internal network calls.
Why exists
The state propagation problem. In standard Node.js server frameworks, passing data through complex middleware chains requires attaching properties to the request object, which is often untyped and prone to conflicts. event.locals provides a type-safe, dedicated space for this data.
The browser/server disconnect. Handling cookies manually using raw HTTP headers is error-prone. event.cookies provides a high-level API that automatically handles encoding, secure flags, and path management, ensuring cookies are consistent between server-side execution and client-side consumption.
The internal API communication problem. When a server-side load function makes a request to its own API, a global fetch might not have the correct context (like auth cookies). event.fetch intercepts these calls, allowing SvelteKit to forward session data automatically without custom logic.
The dependency injection requirement. SvelteKit functions need a consistent interface that doesn’t depend on global variables or environmental imports. By using a single RequestEvent object, developers can unit test functions by passing a mock event, without needing a running server.
The middleware pipeline visibility. Because every hook, load, and action receives this same object, it creates a “traceable” request lifecycle. Any changes made to locals in a hook are visible immediately to all downstream functions, creating a predictable flow of information.
a. event.locals: The request-specific state container
The event.locals object is a plain JavaScript object intended to store data that needs to be accessible throughout the duration of a single request. It is typically populated in the handle hook in hooks.server.js, where you perform your authentication checks.
// hooks.server.js
export async function handle({ event, resolve }) {
const token = event.cookies.get('session');
// Populate locals so load functions can access it
event.locals.user = await getUserFromToken(token);
return resolve(event);
}
Once populated, any +page.server.js or +layout.server.js can read locals.user. To maintain type safety, you must extend the App.Locals interface in your app.d.ts file, ensuring your editor provides autocomplete for the data you store there.
b. event.cookies: Secure session management
The event.cookies API is a wrapper for reading, setting, and deleting cookies. Unlike document.cookie in the browser, this API is strictly server-side and requires a path parameter for many operations, ensuring cookies are scoped correctly to the application.
// +page.server.js
export const actions = {
login: async ({ cookies, request }) => {
const data = await request.formData();
cookies.set('session', data.get('token'), {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 60 * 60 * 24 // 24 hours
});
}
};
Using event.cookies ensures your application follows security best practices automatically. The httpOnly flag is crucial, as it prevents client-side JavaScript from accessing your session tokens, mitigating XSS risks.
c. event.fetch: Context-aware network requests
event.fetch is a specialized version of the standard fetch API. When you use it on the server, it is “smarter” than a standard fetch because it understands the SvelteKit environment. It allows you to call routes within your own application (using relative URLs) without going through the public network.
// +page.server.js
export async function load({ fetch }) {
// Uses internal SvelteKit routing
const response = await fetch('/api/user-profile');
const user = await response.json();
return { user };
}
If you call fetch('/api/user'), SvelteKit will intercept this and route it directly to the internal handler, preserving headers and cookies from the original request. This makes your code cleaner and more efficient by avoiding unnecessary round-trips to the server’s own public IP address.
Complete Example Session
// ============================================
// PART 1: THE HANDLE HOOK POPULATES LOCALS
// ============================================
export async function handle({ event, resolve }) {
event.locals.user = { id: 1, role: 'admin' };
return resolve(event);
}
// ============================================
// PART 2: ACCESSING LOCALS IN LOAD
// ============================================
export async function load({ locals }) {
return { userId: locals.user.id };
}
// ============================================
// PART 3: SETTING COOKIES IN ACTION
// ============================================
export const actions = {
default: ({ cookies }) => {
cookies.set('theme', 'dark', { path: '/' });
}
};
// ============================================
// PART 4: USING EVENT.FETCH
// ============================================
export async function load({ fetch }) {
const data = await fetch('/api/data').then(r => r.json());
return { data };
}
// ============================================
// PART 5: DELETING COOKIES
// ============================================
export const actions = {
logout: ({ cookies }) => {
cookies.delete('session', { path: '/' });
}
};
These parts show the standard flow: authenticating in a hook, passing data through locals, performing actions with cookies, and utilizing the optimized event.fetch for data retrieval.
Quick Reference
event.locals
| Method/Prop | Description |
|---|---|
locals | Object for request state |
App.Locals | TypeScript interface extension |
event.cookies
| Method | Signature |
|---|---|
get(name) | Returns value or undefined |
set(name, value, opts) | Sets a new cookie |
delete(name, opts) | Removes a cookie |
event.fetch
| Feature | Behavior |
|---|---|
| Relative URLs | Bypasses public network |
| Auth context | Automatically forwarded |
| SSR performance | Faster inter-process calls |
Best Practices
✅ Do This:
// Extend App.Locals for TypeScript
interface Locals { user: User; } // ✅
// Always set path when managing cookies
cookies.set('id', '123', { path: '/' }); // ✅
// Use event.fetch for internal calls
const data = await fetch('/api/internal'); // ✅
❌ Don’t Do This:
// Don't store large objects in locals
locals.hugeData = new BigBuffer(); // ❌
// Don't forget path when deleting cookies
cookies.delete('session'); // ❌
// Don't use global fetch for internal API calls
const data = await globalThis.fetch('http://localhost/api'); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Missing Type | locals isn’t defined in d.ts | Update app.d.ts |
| Cookie mismatch | Path not specified in delete | Always provide path: '/' |
| Fetch Loop | fetch called on own endpoint | Use event.fetch |
| Memory usage | Storing full user objects in locals | Store only IDs/Tokens |
Real-World Examples
1. Set Session Cookie
cookies.set('sid', token, { httpOnly: true, secure: true });
2. Get User ID from Locals
const { id } = locals.user;
3. Proxy Internal API
const res = await fetch('/api/backend/data');
4. Clear Session
cookies.delete('sid', { path: '/' });
5. Inject Security Header
cookies.set('X-Frame', 'deny', { path: '/' });
6. Read Cookie
const theme = cookies.get('theme');
7. Update User Local
locals.user.lastSeen = new Date();
8. Check Auth
if (!locals.user) throw redirect(302, '/login');
9. Fetch Config
const cfg = await fetch('/config.json').then(r => r.json());
10. Pass Data to UI
return { userId: locals.user.id };
Visual
The Request Lifecycle
┌─────────────────────────────────────────────────────────┐
│ Incoming Request │
│ │ │
│ ▼ │
│ hooks.server.js ──► event.locals (Populate) │
│ │ │
│ ▼ │
│ Load Functions ──► Read locals, event.fetch │
│ │ │
│ ▼ │
│ Actions ──► event.cookies (Modify) │
│ │ │
│ ▼ │
│ Outgoing Response │
└─────────────────────────────────────────────────────────┘
Cookie Lifecycle
┌─────────────────────────────────────────────────────────┐
│ Browser Request (Headers) ──► Server event.cookies │
│ │ │
│ ▼ │
│ cookies.get() ──► Authentication Verification │
│ │ │
│ ▼ │
│ cookies.set() ──► Response Header (Set-Cookie) │
│ │ │
│ ▼ │
│ Browser Update (Local Cookie Store) │
└─────────────────────────────────────────────────────────┘
Fetch Interception
┌─────────────────────────────────────────────────────────┐
│ Standard fetch() ──► External Network (Slow) │
│ │
│ event.fetch() ──► SvelteKit Internal Routing (Fast) │
│ ┌───────────────────────────────────────────────────┐ │
│ │ 1. Check headers/cookies │ │
│ │ 2. Direct Route Execution │ │
│ │ 3. Return JSON Response │ │
│ └───────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Event Object | RequestEvent |
| Locals API | event.locals |
| Cookie API | event.cookies |
| Fetch API | event.fetch |
| Type definition | app.d.ts |
| Middleware usage | Available in all server functions |
Key takeaways:
event.localsis your shared state. It is the primary way to pass data from middleware hooks to load functions. Always define types inapp.d.ts.event.cookiesmanages browser sessions. It provides a secure, easy-to-use interface to get, set, and delete cookies with correct paths.event.fetchoptimizes your data flow. Use it for internal API calls to avoid unnecessary network latency and to preserve auth headers automatically.RequestEventis ubiquitous. It is the first argument inhooks.server.js,+page.server.js, and actions, making it the most important object in the SvelteKit server lifecycle.- Security is built-in. Using
event.cookiesand following best practices helps enforce HttpOnly and Secure flags, protecting your users from common web attacks.
Remember: The RequestEvent object encapsulates the entire lifecycle of a request. By leveraging locals for state, cookies for storage, and fetch for internal communication, you build a robust server-side architecture that is both type-safe and performant. Treating this object as the single source of truth for your request context is the hallmark of a maintainable, enterprise-grade SvelteKit application.
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!