Ping CronMissed from Node.js
On this page
Node 18 and later ship fetch and AbortSignal.timeout, so a ping needs no dependency. This wrapper reports the start, then success, or failure with the end of the stack trace, and it never lets a failed ping throw.
What should a Node.js job send?
- A request to
/startbefore the work, so CronMissed can time the run and notice a job that never finishes. - A request to the plain URL when the work succeeded, or to
/failwhen it did not./<exit status>works too: 0 is a success and any other number is a failure. - The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.
What is the wrapper?
monitored.mjs
const PING_URL = process.env.CRONMISSED_PING_URL;
async function ping(suffix = '', body) {
try {
await fetch(PING_URL + suffix, {
method: body ? 'POST' : 'GET',
body,
signal: AbortSignal.timeout(10_000),
});
} catch {
// a lost ping must never break the job
}
}
export async function monitored(job) {
await ping('/start');
try {
const result = await job();
await ping();
return result;
} catch (error) {
await ping('/fail', String(error?.stack ?? error).slice(-100_000));
throw error;
}
}
await monitored(async () => {
// the work
});Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.
Which schedulers does this fit?
The same wrapper works in a Vercel route handler, a Cloudflare scheduled handler, an AWS Lambda, a node-cron task and a Railway cron service. Await the pings before the process exits; in serverless runtimes an unawaited request can be cut off when the function returns.
Questions and answers
- No, on current Node versions. fetch is built in, and a ping is one request.
- In a serverless function the runtime may freeze the process as soon as the handler returns, so a request that was not awaited can be lost. In a long-running server it does not matter.
Do I need node-fetch or axios?
Why await the ping?
Create the check these snippets report to
Make a check, copy its ping URL into the snippet, and run the job once.
Start monitoring