A way to validate things on server initialization
See original GitHub issueDescribe the problem
Related to #1538.
In other server solutions, a common pattern is check for the presence of necessary environment variables on startup, for the purposes of showing a friendly error message.
For example:
const { DATABASE_URI } = process.env;
if (DATABASE_URI === undefined || DATABASE_URI === "") {
console.error(
'The "DATABASE_URI" environment variable is not set. This is necessary in order for the server to function.',
);
console.error(
'If you are deploying to Node, did you forget to copy the ".env.example" file to ".env" and fill in the values?',
);
console.error(
"If you are deploying to Vercel, did you forget to add this environment variable to your project settings page?",
);
process.exit(1);
}
Doing this kind of thing prevents end-users from having to troubleshoot more-complicated run-time errors. (“Why is the database logic failing? Is the app that I just downloaded bugged?”)
In #1538, Rich-Harris recommends using “hooks.js”, but this doesn’t solve the problem, as the logic in that file will only be executed when a user actually surfs to the page, rather than on server initialization.
Describe the proposed solution
SvelteKit should expose an idiomatic way to perform server-start validation of this manner.
This would also an appropriate place to e.g. initiate necessary database connections, so that the app can e.g. fail early if the database password is wrong (rather than when the first user actually tries to use your product).
Importance
nice to have
Issue Analytics
- State:
- Created a year ago
- Comments:5 (4 by maintainers)
The only way to surface runtime errors is by actually running the app, and there’s no environment-agnostic way to do that as part of a build step (e.g. in the Vercel case, we’d need to access the deployment, but deployment doesn’t happen until after the build step is complete).
We could surface startup errors immediately rather than waiting for the first request, just by moving this logic… https://github.com/sveltejs/kit/blob/9a110f5fdd9aac3eac4bc09385f5b776a85f2355/packages/kit/src/vite/build/build_server.js#L109-L116 …into the
server.init(...)
method (which would becomeawait server.init(...)
): https://github.com/sveltejs/kit/blob/9a110f5fdd9aac3eac4bc09385f5b776a85f2355/packages/kit/src/vite/build/build_server.js#L87-L102I think we should do that; it would help in the
adapter-node
case, and provides all the benefits of a dedicatedstartup
hook without the downsides. But it wouldn’t be a general solution to this problem because I don’t think there is a general solution.I’ve argued several times for a “startup” hook that’s guaranteed to run right when you start your built app. I think there are many reasons to provide one, this being one of them, but it’s also not super straightforward when it should run, especially in environments with the concept of instances, such as serverless platforms.