DEV Community

Nivethan
Nivethan

Posted on

SvelteKit Hooks

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

export async function handle({ event, resolve }) {
    event.locals.db = "Hello";
    const response = await resolve(event);
    return response;
}
Enter fullscreen mode Exit fullscreen mode

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);
    ...
}
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (1)

Collapse
 
ogrotten profile image
ogrotten

Thanks for this example.