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
—true
if the browser is requesting data for a page during client-side navigation,false
if a page/route is being requested directlylocals
— a place to put arbitrary dataparams
— the route parametersrequest
— the Request objectroute
— an object with anid
property 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.js
export async function handle({ event, resolve }) {
event.locals.answer = 42;
return await resolve(event);
}
src/routes/+page.server.js
export function load(event) {
return {
message: `the answer is ${event.locals.answer}`
};
}