Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Monitor a Small Node.js SaaS Without a Metrics Stack

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Optionally send an email or a message via a webhook
  4. Common Mistakes
  5. Tips
  6. Troubleshooting
  7. Frequently Asked Questions

Running a small Node.js SaaS often means you don't have the time or budget for a full metrics stack like Prometheus, Grafana, or Datadog. This guide shows you how to monitor your app's health and performance using only built-in Node.js modules and simple text files. You'll get uptime alerts, error logging, and basic performance tracking without installing a single new dependency.

What You'll Need

  • A Node.js app already running in production (or a staging environment you can test on).
  • Access to the server's command line (SSH or similar).
  • Basic familiarity with JavaScript and shell commands.
  • Optional: a free cron service (like cron-job.org) or a server cron job to run periodic checks.

Step-by-Step

  1. Create a health check endpoint. In your main server file (e.g., app.js or server.js), add a route that returns a 200 status when the app is alive. For Express, it looks like this:
    app.get('/health', (req, res) => {
      res.status(200).json({ status: 'ok', timestamp: Date.now() });
    });
    If you're using plain Node's http module, handle the /health path in your request listener.
  2. Add a simple request logger. Create a middleware that logs each request to a file. Use Node's built-in fs module to append a line per request. Example:
    const fs = require('fs');
    app.use((req, res, next) => {
      const line = `${new Date().toISOString()} ${req.method} ${req.url} ${res.statusCode}\n`;
      fs.appendFile('requests.log', line, (err) => { if (err) console.error(err); });
      next();
    });
    This gives you a basic access log without external tools.
  3. Capture uncaught exceptions and unhandled rejections. In your main entry file, add:
    process.on('uncaughtException', (err) => {
      fs.appendFile('errors.log', `${new Date().toISOString()} UNCAUGHT: ${err.stack}\n`, () => {
        process.exit(1); // restart via a process manager
      });
    });
    process.on('unhandledRejection', (reason) => {
      fs.appendFile('errors.log', `${new Date().toISOString()} REJECTION: ${reason}\n`);
    });
    This ensures you know when something crashes or a promise fails silently.
  4. Log response times for slow requests. Enhance your request logger to measure duration:
    app.use((req, res, next) => {
      const start = Date.now();
      res.on('finish', () => {
        const duration = Date.now() - start;
        if (duration > 1000) { // log only slow requests
          fs.appendFile('slow.log', `${new Date().toISOString()} ${req.method} ${req.url} ${duration}ms\n`, () => {});
        }
      });
      next();
    });
    This helps you spot performance bottlenecks without a metrics dashboard.
  5. Set up a simple uptime check using a cron job. On your server, create a shell script that curls your health endpoint and sends an alert if it fails. For example, create check_health.sh:
    #!/bin/bash
    response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health)
    if [ "$response" != "200" ]; then
      echo "Health check failed at $(date)" >> /var/log/health_alerts.log
    

    Optionally send an email or a message via a webhook

    fi
    Then add a cron job to run it every minute: * * * * * /path/to/check_health.sh.
  6. Monitor disk space and memory usage. Create another script that checks df -h and free -m, and logs warnings if thresholds are exceeded. Add it to cron.
  7. Use a process manager to auto-restart. If you're not already using PM2 or a similar tool, install PM2 globally (npm install -g pm2) and run your app with it. PM2 keeps your app alive, restarts it on crashes, and gives you basic logs via pm2 logs. This is not a metrics stack, but it's a critical safety net.
  8. Review your logs periodically. Set a weekly calendar reminder to check requests.log, errors.log, and slow.log. Look for trends: increasing error rates, slow endpoints, or unusual request patterns.

Common Mistakes

  • Logging too much. Logging every request to a file can fill your disk quickly. Rotate logs or log only errors and slow requests.
  • Forgetting to handle log write errors. If the disk is full, fs.appendFile will fail silently. Add error callbacks that log to console.
  • Not testing the health endpoint. Make sure your health check doesn't require authentication or a database connection that might fail in a way that doesn't reflect actual health.
  • Ignoring unhandled rejections. Many developers only handle uncaughtException. Unhandled rejections can cause memory leaks and strange behavior.
  • Using a single log file without rotation. Over time, files become huge and hard to search. Use a simple rotation script or the logrotate utility.

Tips

  • Use a free external uptime monitor. Services like UptimeRobot (free tier) can ping your health endpoint from outside and email you if it's down. This catches server-wide outages.
  • Add a simple in-memory counter for requests. If you want a quick metric without logging every request, increment a global counter and expose it in your health endpoint as JSON.
  • Separate logs by level. Use errors.log, warn.log, and info.log to make filtering easier.
  • Use PM2's built-in metrics. PM2 can show CPU and memory usage per process via pm2 monit. It's not a full stack, but it's useful for quick checks.
  • Set up a simple webhook alert. If you use Slack or Discord, you can send a POST request to a webhook URL when the health check fails. This is easier than configuring email.

Troubleshooting

  • Health check returns 404. Make sure the route is defined before any catch-all middleware or 404 handler.
  • Logs are empty. Check file permissions. The process may not have write access to the directory. Run chmod 755 on the directory or use an absolute path.
  • App crashes but no error logged. If the crash happens before your process.on handlers are registered, they won't catch it. Register them at the very top of your entry file.
  • Cron job doesn't run. Verify the script is executable (chmod +x check_health.sh) and that the cron syntax is correct. Check the cron log (/var/log/syslog on Ubuntu) for errors.
  • Slow request log is too large. Increase the threshold (e.g., log only requests over 2 seconds) or implement log rotation.
  • PM2 restarts but app still fails. Check pm2 logs to see the actual error. It might be a configuration issue, not a code crash.

Frequently Asked Questions

  1. Can I do this without writing any code? You can use PM2's built-in logs and a cron job with curl, but adding a health endpoint and error handlers requires a few lines of code. It's minimal and worth it.
  2. Is this enough for a production app? For a small SaaS with low traffic, yes. It gives you crash detection, error logs, and basic performance alerts. As you grow, you can migrate to a full metrics stack.
  3. How do I rotate logs manually? Use logrotate on Linux. Create a config file in /etc/logrotate.d/ specifying the log path, rotation frequency, and number of old logs to keep.
  4. What if my health endpoint requires a database connection? That's fine, but be aware that a database outage will trigger alerts even if your app is otherwise healthy. Consider a separate endpoint that only checks the process is alive.
  5. Can I monitor multiple instances? Yes, run the same health check script against each instance's port. You can also add a simple load balancer check.
  6. Is there a way to get alerts without email? Use a webhook to a messaging app like Slack or Discord. Many free services allow this with a simple POST request.