home
sveltekit-hooks.md

SvelteKit Hooks

2022-04-30

A quick snippet to use sveltekit hooks because there isn’t anything super obvious online.

It’s a pretty simple idea. Hooks are functions that run on the server before each request, so in a hook file you can open a db, then inside the handle function that runs, add the connection to the locals variable which will then be available in the various http functions.

./src/hooks.js

const db = "hello";

export async function handle({ event, resolve }) {
    event.locals.db = db;
    const response = await resolve(event);
    return response;
}

Now we have the db variable in our locals, which will pass to the get function.

./src/routes/[id].js

export function get({ locals, url, params }) {
    console.log(locals.db);
    ...
}

I think a bit more obvious documentation would be nice as my biggest issue was that I knew what sveltekit was doing but I wasn’t sure how it was doing it.

The other thing to note is that locals isn’t available in the load function. It’s only available server side in the endpoints. To get locals into the load function, you would need to use the getSession function in hooks to add information to the request that goes out to the client.

Some cool ideas in all this.