DEV Community

Nivethan
Nivethan

Posted on

3 2

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (1)

Collapse
 
ogrotten profile image
ogrotten

Thanks for this example.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay