How To Run A Function Once On Startup Using SvelteKit (node-adapter)

No Comments
Published: 14.04.2024

Do you want to run a function once on startup in your SvelteKit application, for example, to schedule all your cron tasks? In this quick guide, I will show you exactly how to do so.

Run a function once on startup using SvelteKit

Before we can start, make sure that your current adapter is set to a node adapter so that we can execute the function once on the server side of the application. I am pretty sure that it also works with other adapters (e.g. vercel) besides maybe the static adapter.
After you have selected the node adapter for your project and then go to your src/hooks.server.js/ts file or create one in case you haven’t yet. Inside the hooks.server.ts file, you usually define functions that respond to specific events inside your application, for example, the handle function that runs every time the server gets a request. In this post, we used this function for authentication and authorization in combination with Pocketbase.

To now create the function that should be called once, we need to specify our own. For example, we can create a function called startJobs, and add it to the beginning of our hooks.server.ts file. As it is not related to any built-in function, it will be called once as soon as the server starts. The final code could look something like this:

import { building } from '$app/environment';

if (!building) {
    startJobs();
}

/// type: import('@sveltejs/kit').Handle
export const authorization: Handle = async ({ event, resolve }) => {
    // ...
};

export const handle = sequence(
    // ...
    authorization
);

Here I added the !building check to make sure it is not called during the build process of the application.

Conclusion

With that you learned how to call a function once on the startup of your SvelteKit server using the node-adapter. I hope this quick guide was helpful to you and if you have any questions feel free to ask!

In case you liked this guide consider subscribing to my newsletter.

Need help or want to share feedback? Join my discord community!

[convertkit form=2303042]

Discussion (0)