Monitor a Small Node.js SaaS Without a Metrics Stack
In this article
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
- Create a health check endpoint. In your main server file (e.g.,
app.jsorserver.js), add a route that returns a 200 status when the app is alive. For Express, it looks like this:
If you're using plain Node'sapp.get('/health', (req, res) => { res.status(200).json({ status: 'ok', timestamp: Date.now() }); });httpmodule, handle the/healthpath in your request listener. - Add a simple request logger. Create a middleware that logs each request to a file. Use Node's built-in
fsmodule to append a line per request. Example:
This gives you a basic access log without external tools.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(); }); - Capture uncaught exceptions and unhandled rejections. In your main entry file, add:
This ensures you know when something crashes or a promise fails silently.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`); }); - Log response times for slow requests. Enhance your request logger to measure duration:
This helps you spot performance bottlenecks without a metrics dashboard.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(); }); - 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:
Then add a cron job to run it every minute:#!/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.logOptionally send an email or a message via a webhook
fi* * * * * /path/to/check_health.sh. - Monitor disk space and memory usage. Create another script that checks
df -handfree -m, and logs warnings if thresholds are exceeded. Add it to cron. - 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 viapm2 logs. This is not a metrics stack, but it's a critical safety net. - Review your logs periodically. Set a weekly calendar reminder to check
requests.log,errors.log, andslow.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.appendFilewill 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
logrotateutility.
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, andinfo.logto 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 755on the directory or use an absolute path. - App crashes but no error logged. If the crash happens before your
process.onhandlers 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/syslogon 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 logsto see the actual error. It might be a configuration issue, not a code crash.
Frequently Asked Questions
- 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.
- 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.
- How do I rotate logs manually? Use
logrotateon Linux. Create a config file in/etc/logrotate.d/specifying the log path, rotation frequency, and number of old logs to keep. - 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.
- 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.
- 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.