sveltekit

How to execute code on SvelteKit app start up


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?


Solution

  • Update Jan 2025

    @Matthias Mertens has a helpful hint in the comments of another answer that hooks.server.ts only runs on the first request in dev mode, but will run at startup in prod. But there is now an init() for anyone coming here in 2025.

    In hooks.server.ts:

    import type { ServerInit } from '@sveltejs/kit';
    import * as db from '$lib/db';
    
    export const init: ServerInit = async () => {
        await db.connect()
    };