惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LINUX DO - 最新话题
Recorded Future
Recorded Future
月光博客
月光博客
博客园 - 【当耐特】
博客园 - 叶小钗
宝玉的分享
宝玉的分享
量子位
雷峰网
雷峰网
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
Vercel News
Vercel News
L
LangChain Blog
B
Blog
Y
Y Combinator Blog
爱范儿
爱范儿
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
博客园 - Franky
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
C
Cisco Blogs
Scott Helme
Scott Helme
I
Intezer
T
The Exploit Database - CXSecurity.com
MyScale Blog
MyScale Blog
T
Tor Project blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Troy Hunt's Blog
N
News and Events Feed by Topic
大猫的无限游戏
大猫的无限游戏
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
Security Affairs
Cyberwarzone
Cyberwarzone
PCI Perspectives
PCI Perspectives
小众软件
小众软件
D
DataBreaches.Net
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
Forbes - Security
Forbes - Security
S
Securelist
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
The Last Watchdog
The Last Watchdog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Lightweight Website Monitor with Cron and an API
Sen Shi · 2026-05-07 · via DEV Community

You can build a working website change monitor in under 100 lines of Node.js. No database, no queue, no container orchestration. Just cron, a screenshot API, pixelmatch, and a notification hook. The whole thing runs on a $5/mo VPS or a free GitHub Actions workflow.

Here's the full build, from first line to deployment.

The Stack

Component Tool Cost
Scheduler System cron or node-cron Free
Screenshot capture Screenshot API (GET request) Free tier / $9 mo
Image comparison pixelmatch Free (npm)
Notification Slack webhook or email (nodemailer) Free
Storage Local filesystem Free

Total infrastructure cost: $0-5/month. Screenshot API cost depends on how many URLs you monitor and how often. Twenty URLs captured once daily is 600 screenshots per month, which fits comfortably in the free tier of most providers.

Prerequisites

mkdir website-monitor && cd website-monitor
npm init -y
npm install pngjs pixelmatch nodemailer

Enter fullscreen mode Exit fullscreen mode

That's three dependencies. pngjs parses PNG buffers. pixelmatch does pixel-level comparison. nodemailer sends email alerts (swap this for a Slack webhook fetch if you prefer).

The Complete Script

This is the entire monitor. Under 100 lines of actual logic.

// monitor.js
import fs from "fs/promises";
import path from "path";
import { PNG } from "pngjs";
import pixelmatch from "pixelmatch";
import nodemailer from "nodemailer";

// ─── Config ──────────────────────────────────────────────
const SCREENSHOT_API = "<your api of choise>";
const API_KEY = process.env.SCREENSHOT_API_KEY;
const STORAGE = process.env.STORAGE_DIR || "./captures";
const DIFF_THRESHOLD = 0.005; // 0.5% of pixels must differ

const URLS = [
  { name: "competitor-pricing", url: "https://competitor.com/pricing" },
  { name: "partner-terms", url: "https://partner.com/terms" },
  { name: "our-homepage", url: "https://our-app.com" },
];

const EMAIL = {
  from: "monitor@yourdomain.com",
  to: "you@yourdomain.com",
  smtp: {
    host: process.env.SMTP_HOST || "smtp.mailgun.org",
    port: 587,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  },
};

// ─── Capture ─────────────────────────────────────────────
async function capture(url) {
  const params = new URLSearchParams({
    url,
    format: "png",
    width: "1280",
    height: "800",
    full_page: "true",
    block_ads: "true",
    block_cookie_banners: "true",
  });

  const res = await fetch(`${SCREENSHOT_API}?${params}`, {
    headers: { "X-API-Key": API_KEY },
  });

  if (!res.ok) throw new Error(`API ${res.status}: ${res.statusText}`);
  return Buffer.from(await res.arrayBuffer());
}

// ─── Compare ─────────────────────────────────────────────
function compare(bufA, bufB) {
  const a = PNG.sync.read(bufA);
  const b = PNG.sync.read(bufB);

  if (a.width !== b.width || a.height !== b.height) {
    return { changed: true, pct: 100 };
  }

  const { width, height } = a;
  const diff = new PNG({ width, height });
  const badPixels = pixelmatch(
    a.data, b.data, diff.data,
    width, height,
    { threshold: 0.1 }
  );

  const pct = (badPixels / (width * height)) * 100;
  return { changed: pct / 100 > DIFF_THRESHOLD, pct, diffBuf: PNG.sync.write(diff) };
}

// ─── Alert ───────────────────────────────────────────────
async function alert(site, pct, diffBuf) {
  const transport = nodemailer.createTransport(EMAIL.smtp);
  await transport.sendMail({
    from: EMAIL.from,
    to: EMAIL.to,
    subject: `[Monitor] ${site.name} changed (${pct.toFixed(2)}%)`,
    text: `${site.url} has changed by ${pct.toFixed(2)}%.\nDiff image attached.`,
    attachments: diffBuf
      ? [{ filename: "diff.png", content: diffBuf }]
      : [],
  });
}

// ─── Main loop ───────────────────────────────────────────
async function run() {
  for (const site of URLS) {
    const dir = path.join(STORAGE, site.name);
    await fs.mkdir(dir, { recursive: true });

    const latestPath = path.join(dir, "latest.png");
    const prevPath = path.join(dir, "previous.png");

    try {
      const screenshot = await capture(site.url);

      // Load previous capture if it exists
      let prev = null;
      try {
        prev = await fs.readFile(latestPath);
      } catch {
        // First run, no previous file
      }

      if (prev) {
        const result = compare(prev, screenshot);
        const status = result.changed ? "CHANGED" : "ok";
        console.log(`${site.name}: ${result.pct.toFixed(2)}% diff [${status}]`);

        if (result.changed) {
          await alert(site, result.pct, result.diffBuf);
          // Archive the previous version
          const ts = new Date().toISOString().replace(/[:.]/g, "-");
          await fs.copyFile(latestPath, path.join(dir, `${ts}.png`));
        }
      } else {
        console.log(`${site.name}: first capture`);
      }

      // Rotate: current latest becomes previous, new capture becomes latest
      try {
        await fs.copyFile(latestPath, prevPath);
      } catch {
        // No latest yet
      }
      await fs.writeFile(latestPath, screenshot);
    } catch (err) {
      console.error(`${site.name}: ${err.message}`);
    }
  }
}

run();

Enter fullscreen mode Exit fullscreen mode

What Each Step Does

  1. Capture: sends a GET request to the screenshot API with the target URL. Returns a PNG buffer. Full-page capture with ad blocking and cookie banner removal keeps the captures clean.

  2. Load previous: reads latest.png from the site's directory. On first run this file doesn't exist, so we skip comparison and just save.

  3. Compare: pixelmatch walks both images pixel by pixel. The threshold: 0.1 option handles anti-aliasing and sub-pixel rendering differences. We calculate the percentage of pixels that differ.

  4. Alert: if the diff exceeds 0.5%, we send an email with the diff image attached. The diff image highlights changed pixels in red, making it easy to spot what moved.

  5. Save: the new screenshot becomes latest.png. If a change was detected, we also archive the old version with a timestamp so you have a history of what changed and when.

No database needed. The filesystem is your storage. Each monitored URL gets a directory, each directory holds latest.png, previous.png, and any archived snapshots from detected changes.

Swapping Email for Slack

If your team lives in Slack, replace the alert function:

async function alert(site, pct) {
  const webhook = process.env.SLACK_WEBHOOK_URL;
  await fetch(webhook, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      blocks: [
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: `*Website change detected*\n<${site.url}|${site.name}>: ${pct.toFixed(2)}% different`,
          },
        },
      ],
    }),
  });
}

Enter fullscreen mode Exit fullscreen mode

For Slack image attachments, you'd need to upload the diff image to a public URL (S3, R2, or your own server) and include it in the block. For most cases, the text notification is enough to prompt someone to go look.

Deployment Options

Option 1: $5/mo VPS

Any cheap VPS (Hetzner, DigitalOcean, Vultr) works. Install Node.js, clone your monitor, set up cron.

# Install
ssh root@your-vps
apt update && apt install -y nodejs npm
git clone https://github.com/you/website-monitor.git /opt/monitor
cd /opt/monitor && npm install

# Environment
cat > /opt/monitor/.env << 'EOF'
SCREENSHOT_API_KEY=your_key_here
SMTP_HOST=smtp.mailgun.org
SMTP_USER=postmaster@yourdomain.com
SMTP_PASS=your_smtp_password
STORAGE_DIR=/opt/monitor/captures
EOF

# Cron: run daily at 9 AM UTC
crontab -e
# Add:
0 9 * * * cd /opt/monitor && env $(cat .env | xargs) node monitor.js >> /var/log/monitor.log 2>&1

Enter fullscreen mode Exit fullscreen mode

Option 2: Raspberry Pi

Same setup as the VPS but runs on your local network. Good if you want to avoid monthly hosting costs and don't mind the Pi being on 24/7. Use node-cron instead of system cron for easier management:

import cron from "node-cron";
import { run } from "./monitor.js";

cron.schedule("0 9 * * *", () => {
  console.log(`[${new Date().toISOString()}] Running check...`);
  run().catch(console.error);
});

console.log("Monitor started. Checking daily at 09:00.");

Enter fullscreen mode Exit fullscreen mode

Option 3: GitHub Actions (Free)

This is the zero-infrastructure option. No server to maintain. GitHub gives you 2,000 minutes/month on the free plan, and each monitor run takes under a minute.

# .github/workflows/monitor.yml
name: Website Monitor

on:
  schedule:
    - cron: "0 9 * * *"  # Daily at 9 AM UTC
  workflow_dispatch:       # Manual trigger

jobs:
  monitor:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - run: npm ci

      - name: Download previous captures
        uses: actions/download-artifact@v4
        with:
          name: captures
          path: ./captures
        continue-on-error: true  # First run has no artifact

      - name: Run monitor
        env:
          SCREENSHOT_API_KEY: ${{ secrets.SCREENSHOT_API_KEY }}
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: node monitor.js

      - name: Upload captures
        uses: actions/upload-artifact@v4
        with:
          name: captures
          path: ./captures
          retention-days: 30

Enter fullscreen mode Exit fullscreen mode

The trick is using GitHub Actions artifacts to persist screenshots between runs. download-artifact grabs the previous captures, the script runs and compares, then upload-artifact saves the new state.

Limitation: artifacts are retained for a maximum of 90 days, and storing large numbers of screenshots will eat into your storage quota. For 20 URLs, this is fine. For 200, use a VPS.

Dealing with Noise

The first time you run website change monitoring with screenshots, you'll get false positives. Dynamic content like timestamps, ad rotations, and chat widgets cause small differences on every capture.

Three fixes:

1. Hide noisy elements. Add hide_selectors to your API call to remove dynamic content before capture:

const params = new URLSearchParams({
  url,
  format: "png",
  width: "1280",
  full_page: "true",
  block_ads: "true",
  block_cookie_banners: "true",
  hide_selectors: ".chat-widget,.timestamp,.ad-slot,.visitor-count",
});

Enter fullscreen mode Exit fullscreen mode

2. Raise the threshold for noisy pages. Instead of a global 0.5% threshold, use per-URL thresholds:

const URLS = [
  { name: "legal-page", url: "https://example.com/terms", threshold: 0.001 },
  { name: "news-site", url: "https://news.example.com", threshold: 0.03 },
  { name: "pricing", url: "https://competitor.com/pricing", threshold: 0.005 },
];

Enter fullscreen mode Exit fullscreen mode

Then in the comparison: result.pct / 100 > site.threshold.

3. Use a file size pre-check. If the PNG file size barely changed, skip the expensive pixel comparison entirely:

function quickCheck(bufA, bufB) {
  const sizeDiff = Math.abs(bufA.length - bufB.length) / bufA.length;
  return sizeDiff > 0.05; // Only run pixelmatch if size changed > 5%
}

Enter fullscreen mode Exit fullscreen mode

Monitoring More URLs Without More Code

The script handles any number of URLs. Just add them to the URLS array. To load targets from a file instead of hardcoding them:

// urls.json
[
  { "name": "competitor-a", "url": "https://a.com/pricing", "threshold": 0.005 },
  { "name": "competitor-b", "url": "https://b.com/pricing", "threshold": 0.005 },
  { "name": "our-terms", "url": "https://our.com/terms", "threshold": 0.001 }
]

Enter fullscreen mode Exit fullscreen mode

const URLS = JSON.parse(
  await fs.readFile("./urls.json", "utf-8")
);

Enter fullscreen mode Exit fullscreen mode

Now adding a new monitored URL is a one-line JSON edit. No code changes, no redeployment.

Cost Breakdown

Monitoring Setup URLs Frequency Monthly Captures API Cost Infra Cost
Minimal 5 Daily 150 Free $0 (GitHub Actions)
Typical 20 Daily 600 Free $0 (GitHub Actions)
Active 20 4x daily 2,400 ~$9/mo $0 (GitHub Actions)
Heavy 50 Hourly 36,000 ~$29/mo $5/mo VPS

For most indie dev use cases, 20 URLs monitored daily lands you at 600 screenshots per month. That's well within the free tier of APIs or barely into the $9/mo starter plan. Website change monitoring with screenshots doesn't have to cost anything meaningful.

Extending the Monitor

Once the base monitor works, useful additions include:

Screenshot history viewer. A simple Express server that lists archived screenshots by URL and date. Ten lines of code to serve the captures/ directory with a file listing.

Change log. Append a line to a CSV or JSON file whenever a change is detected. Over time, this gives you a timeline of when each monitored page changed.

async function logChange(site, pct) {
  const entry = JSON.stringify({
    site: site.name,
    url: site.url,
    diff: pct,
    time: new Date().toISOString(),
  });
  await fs.appendFile("./change-log.jsonl", entry + "\n");
}

Enter fullscreen mode Exit fullscreen mode

Multiple notification channels. Alert via email for critical pages, Slack for informational ones, and a webhook for integration with your internal tools.

The core stays under 100 lines. Each extension adds maybe 10-20 lines. That's the benefit of building your own website change monitoring with screenshots instead of paying for a SaaS tool: you control every part of the pipeline and can add exactly what you need.