Skip to content

Periodically check your website/url with Cloudflare worker

homepage-banner

Here is the minimal example to show how to build your own website check with Cloudflare worker and send IM notice to LINE channel.

Create a new worker project

Quick Edit

const url_list = ["http://your.own.http.site", "https://your.own.https.site"];

async function gatherResponse(response) {
    const { headers } = response;
    // console.log(headers);
    const contentType = headers.get("content-type") || "";
    if (contentType.includes("application/json")) {
        return JSON.stringify(await response.json());
    } else if (contentType.includes("application/text")) {
        return response.text();
    } else if (contentType.includes("text/html")) {
        return response.text();
    } else {
        return response.text();
    }
}

async function handleScheduled(event) {
    const init = {
        headers: {
            "content-type": "text/html;charset=UTF-8",
        },
    };
    for (const url of url_list) {
        const response = await fetch(url, init);
        if (response.status === '301' || '302' || '200') {
            console.log(response.status);
        } else {
            await sendToLineChannel(response.status + ": " + url);
        };
    };
};

addEventListener("scheduled", (event) => {
    event.waitUntil(handleScheduled(event));
});

async function sendToLineChannel(msg) {
    // send to LINE
    const form = new FormData();
    form.append("message", msg);
    const init = {
        method: 'POST',
        headers: {
            "Authorization": "Bearer Your_channel_key"
        },
        body: form
    };
    const response = await fetch("https://notify-api.line.me/api/notify", init);
}

Config Triggers

config Cron Triggers to execute your Worker on a time-based, reoccurring schedule.

Reference

  • https://developers.cloudflare.com/workers/learning/metrics-and-analytics/#requests
  • Alternative solution: https://grafana.com/docs/grafana-cloud/synthetic-monitoring/

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.com, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected
  5. Partial content rewritten by AI, verified by humans
Feedback