How to execute code on SvelteKit app start up

Viewed 919

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?

1 Answers

I believe this can be done with hooks. This is from an example on a question asked here, that would get the user agent on page load.

Create hooks.js inside your src folder:

export function getSession(request) {
    return {
        userAgent: request.headers['user-agent']
    }
}

Then you can use it inside the load function of each component you want:

<script context="module">
    export async function load({ session }) {
        console.log(session.userAgent)
    }
</script>
Related