I have a SvelteKit based application in development. On the server startup, be it on a development server boot up, Node.js adapter boot up I would like to execute some diagnostics commands. An example of such action is to ping the backend server and fail early if the backend is unreachable. This would be mostly a concern for server-side rendering, but if it is easy I would like to apply it for static deployments as well.
What would be the best hook to place in such code?
Also what would be graceful way to abort the application launch with an error message?
By now, there finally seems to be an official answer:
https://kit.svelte.dev/docs/hooks
Hooks
[...]
There are two hooks files, both optional:
- src/hooks.server.js — your app's server hooks
- src/hooks.client.js — your app's client hooks
Code in these modules will run when the application starts up, making them useful for initializing database clients and so on.
[...]
So yes, just put your code in one of the hook.js-files (a top level, not in a function), and it runs at startup.
Edit: As tried out by leumasme (https://github.com/sveltejs/kit/issues/927#issuecomment-1349637401) this only applies to release builds though. In dev mode the code gets executed only with the first request. So keep this in mind.
Solved by a Svelte Ambassador {🧪} pablopang at Svelte's Discord channel. Quote:
if you run the code inside the module of hooks.server.ts it will be exected only once what i mean is that you need to run right inside hooks.server.ts not in the exported handle function
obviosuly be aware of the fact that if you deploy on serverless every new lambda spin up will run that code but that should be good since it's like if you just spun up the server
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With