Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
The event object passed into handle is the same object — an instance of a RequestEvent — that is passed into API routes in +server.js files, form actions in +page.server.js files, and load functions in +page.server.js and +layout.server.js.
It contains a number of useful properties and methods, some of which we’ve already encountered:
cookies— the cookies APIfetch— the standard Fetch API, with additional powersgetClientAddress()— a function to get the client’s IP addressisDataRequest—trueif the browser is requesting data for a page during client-side navigation,falseif a page/route is being requested directlylocals— a place to put arbitrary dataparams— the route parametersrequest— the Request objectroute— an object with anidproperty representing the route that was matchedsetHeaders(...)— a function for setting HTTP headers on the responseurl— a URL object representing the current request
A useful pattern is to add some data to event.locals in handle so that it can be read in subsequent load functions:
src/hooks.server
export async function handle({ event, resolve }) {
event.locals.answer = 42;
return await resolve(event);
}src/routes/+page.server
export function load(event) {
return {
message: `the answer is ${event.locals.answer}`
};
}previous next
1
2
3
4
5
<script>
let { data } = $props();</script>
<h1>{data.message}</h1>