Hooks
A _hook.server.ts file defines functions that run around every request in its folder and the folders below it. A hook at the root of src/routes runs for the whole site:
// routes/_hook.server.ts
import { type ServerHook } from "@torpor/build";
import { getUser } from "@/lib/auth";
export default {
enter: async (event) => {
event.appData.user = await getUser(event.cookies);
},
} satisfies ServerHook;
The enter hook
enter runs before each request is handled, including page loads, actions and API endpoints. Return a Response to short-circuit the request. For example, to redirect users who are not logged in:
enter: async (event) => {
if (!event.appData.user) {
return seeOther("/login");
}
},
The exit hook
exit runs after the request has been handled, even if the handler threw an error or enter short-circuited it. Use it for logging and cleanup.
Shared data
Anything set on event.appData flows down to layouts, pages and endpoints in the same request, so a user loaded in a hook is available everywhere else without fetching it again.