Monitor an Endpoint’s Uptime#

Check that a URL responds, and alert when it does not. Run it every few minutes for a lightweight uptime check, or once an hour for a gentler one.

The Script#

// uptime.js
import env from "env";

const target = "https://example.com/health";

async function alert(message) {
	await fetch(env.get("ALERT_WEBHOOK_URL"), {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({ text: message }),
	});
}

try {
	const res = await fetch(target, { method: "GET" });

	if (res.ok) {
		console.log(`${target} is up (${res.status})`);
	} else {
		console.log(`${target} returned ${res.status}`);
		await alert(`Endpoint down: ${target} returned ${res.status}`);
	}
} catch (error) {
	console.log(`Request failed: ${error.message}`);
	await alert(`Endpoint unreachable: ${target} (${error.message})`);
}

How It Works#

  • A non-OK status and a network failure are handled separately, so the alert can say which happened.
  • The alert goes through a webhook, so this works with Slack, Discord, or any endpoint that accepts a JSON text field. Point ALERT_WEBHOOK_URL at the one you want.
  • The job itself never throws on a failed check, so the run still shows as successful while the alert carries the bad news.

Setup#

Create a secret named ALERT_WEBHOOK_URL with your notification webhook. Change target to the URL you want to watch, then schedule the job, for example */15 * * * *.