· Updated on
Self‑Hosted Analytics for a Personal Blog
How I added privacy‑friendly visitor statistics to a static Astro site using a tiny Node.js endpoint, SQLite, PM2, and Caddy.
Table of Contents
Instead of using third‑party analytics like Cloudflare, I’m running a tiny self‑hosted tracker and you can also learn how it works and replicate it.
What I’ve built
A tiny analytics API that:
- Accepts page‑view pings from this blog (
/v1/ping, which Caddy maps to the app’s internal/trackroute) - Provides comprehensive analytics via
/summaryand/dailyendpoints - Lets me export raw visits as CSV (
/export) - Stores data in a single
SQLitefile for easy backup/migration - Runs forever with
pm2, served over HTTPS withCaddy
You can adapt this for any static site (Astro, Hugo, etc.).
0) Prerequisites
- A cloud VM with a public IP
- A subdomain of your blog’s own domain for the analytics endpoint (for example
api.example.comfor a blog onexample.com; see the note in section 5 for why this matters) - Basic DNS access (Cloudflare etc.)
- Node.js 18+ and npm
WARNING
Debian/Ubuntu users: Do not use sudo apt install nodejs npm directly from the default repositories, as they often contain severely outdated Node.js versions (e.g., Node.js 10.x or 12.x) with known security vulnerabilities and no security patches. Always install from NodeSource to get current, supported versions.
Debian/Ubuntu
sudo apt update && sudo apt upgrade -y
# Install latest Node.js LTS from NodeSource
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs git
# Verify installation
node --version # Should show the latest LTS version
npm --version
Fedora CoreOS
IMPORTANT
Fedora CoreOS is an immutable operating system designed for containerized workloads. You cannot install packages directly with dnf install. Instead, use toolbox to create a mutable container environment.
For more information about Fedora CoreOS on GCP, see the official documentation.
Step 1: Create and enter a toolbox
toolbox create
toolbox enter
Step 2: Install Node.js inside the toolbox
# Install Node.js from Fedora's default repositories
sudo dnf install -y nodejs npm git
# Verify installation
node --version # Should show v22.x.x
npm --version
Step 3: Work inside the toolbox
All subsequent commands (creating the project, installing packages, running the server) should be executed inside the toolbox. The toolbox persists across reboots and you can re-enter it anytime with toolbox enter.
TIP
To exit the toolbox, type exit. To re-enter later, use toolbox enter.
1) Create the analytics service
Create a new folder and initialise a Node project:
TIP
I use better-sqlite3 instead of sqlite3 to avoid npm vulnerabilities and get better performance. It’s synchronous (simpler) and has fewer security issues.
mkdir -p ~/page-stats/data && cd ~/page-stats
npm init -y
npm install express better-sqlite3
Create server.js:
const fs = require("fs");
const express = require("express");
const Database = require("better-sqlite3");
const app = express();
app.set("trust proxy", 1);
app.set("json spaces", 2);
fs.mkdirSync("./data", { recursive: true });
const db = new Database("./data/stats.db");
app.use(express.json({ limit: "2kb" }));
app.use(express.text({ type: "text/plain", limit: "2kb" }));
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA busy_timeout = 5000;
`);
db.exec(`CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT,
referrer TEXT,
ua TEXT,
ip TEXT,
ts DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_visits_path ON visits(path)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_visits_ts ON visits(ts)`);
const stmtInsert = db.prepare(
`INSERT INTO visits (path, referrer, ua, ip) VALUES (?, ?, ?, ?)`
);
const stmtExport = db.prepare(
`SELECT * FROM visits ORDER BY ts DESC`
);
const stmtDaily = db.prepare(`
SELECT path, ip, COUNT(*) AS views, MAX(ts) AS last_seen
FROM visits
WHERE ts >= DATE('now', '-30 days')
GROUP BY DATE(ts), path, ip
ORDER BY last_seen DESC
`);
const stmtSummaryTotal = db.prepare(`
SELECT
COUNT(*) AS total_views,
COUNT(DISTINCT path) AS unique_paths,
COUNT(DISTINCT ip) AS unique_visitors,
MIN(ts) AS first_visit,
MAX(ts) AS last_visit
FROM visits
`);
const stmtSummaryByPath = db.prepare(`
SELECT path, COUNT(*) AS views
FROM visits
GROUP BY path
ORDER BY views DESC
`);
const stmtSummaryByDay = db.prepare(`
SELECT DATE(ts) AS day, COUNT(*) AS views
FROM visits
GROUP BY day
ORDER BY day DESC
`);
const stmtSummaryByIp = db.prepare(`
SELECT ip, COUNT(*) AS views
FROM visits
GROUP BY ip
ORDER BY views DESC
`);
app.post("/track", (req, res) => {
let body = req.body;
// Handle both text/plain and JSON input
if (typeof body === "string") {
try {
body = JSON.parse(body);
} catch {
body = {};
}
}
const { path: rawPath, referrer: rawReferrer } = body || {};
const path = typeof rawPath === "string" ? rawPath : "";
const referrer = typeof rawReferrer === "string" ? rawReferrer : "";
// Always read user-agent from the real HTTP header — never trust the client body
const userAgent = req.headers["user-agent"] || "";
const ip = req.ip || "";
if (!path) {
console.warn("[analytics] Missing path field in request body");
return res.sendStatus(400);
}
try {
stmtInsert.run(path, referrer, userAgent, ip);
res.sendStatus(204);
} catch (err) {
console.error("DB insert error:", err);
res.sendStatus(500);
}
});
// Escape a value for safe CSV output
// Doubles any internal quotes (" → "")
// Prefixes values starting with =, +, -, @, tab, or CR with a tab to
// neutralise spreadsheet formula injection (CVE-class: CSV injection)
function csvEscape(val) {
const str = String(val ?? "");
const safe = /^[=+\-@\t\r]/.test(str) ? `\t${str}` : str;
return `"${safe.replace(/"/g, '""')}"`;
}
// CSV export
app.get("/export", (req, res) => {
try {
const rows = stmtExport.all();
const csv = [
"id,path,referrer,ua,ip,ts",
...rows.map(r =>
[r.id, r.path, r.referrer, r.ua, r.ip, r.ts]
.map((v, i) => i === 0 ? r.id : csvEscape(v))
.join(",")
)
].join("\n");
res.setHeader("Content-Disposition", "attachment; filename=stats.csv");
res.type("text/csv").send(csv);
} catch (err) {
res.status(500).send(err.message);
}
});
// --- Daily summary (views per day and path, last 30 days) ---
app.get("/daily", (req, res) => {
try {
res.json(stmtDaily.all());
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// --- Totals summary (overall + by path + by day, all-time) ---
app.get("/summary", (req, res) => {
try {
res.json({
...stmtSummaryTotal.get(),
by_path: stmtSummaryByPath.all(),
by_day: stmtSummaryByDay.all(),
by_ip: stmtSummaryByIp.all(),
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(8080, () => console.log("Analytics server running on port 8080"));
Quick test:
node server.js
In another shell:
curl -X POST http://localhost:8080/track \
-H "Content-Type: text/plain" \
-d '{"path":"/hello","referrer":""}'
curl "http://localhost:8080/summary"
You should see a JSON object with total views and breakdowns.
2) Keep it running in the background
Debian/Ubuntu: pm2
sudo npm install -g pm2
pm2 start server.js --name stats
pm2 startup
# Run the one-line command pm2 prints for systemd, then:
pm2 save
Check status:
pm2 ls
Stop the service:
pm2 stop stats
Restart the service:
pm2 restart stats
Remove from PM2 (stops and removes from process list):
pm2 delete stats
Completely disable PM2 auto-start (removes systemd integration):
pm2 unstartup
# Run the command it suggests with sudo
Or manually disable the systemd service:
sudo systemctl disable pm2-$USER
sudo systemctl stop pm2-$USER
Fedora CoreOS: Podman + Systemd
Step 1: Create a Dockerfile (inside toolbox)
Inside toolbox, in ~/page-stats directory
cat > Dockerfile <<'EOF'
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY server.js ./
RUN mkdir -p /app/data
EXPOSE 8080
CMD ["node", "server.js"]
EOF
Step 2: Exit toolbox and build the container image on the host
exit
On the Fedora CoreOS host, build the image
cd ~/page-stats
podman build -t localhost/page-stats:latest .
Step 3: Create a data directory for persistence
IMPORTANT
Why use a separate data directory: Storing the database in ~/page-stats/data/ keeps it outside the container image, so it persists across container restarts. The application code (server.js, node_modules) stays in the image, so rebuilds with podman build always take effect.
Create the data directory:
mkdir -p ~/page-stats/data
Step 4: Create systemd service
Create systemd user service directory:
mkdir -p ~/.config/systemd/user/
Create the service file:
cat > ~/.config/systemd/user/page-stats.service <<'EOF'
[Unit]
Description=Page Stats Analytics Service
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
Restart=always
RestartSec=10
ExecStartPre=-/usr/bin/podman rm -f -i page-stats
ExecStart=/usr/bin/podman run --rm --name page-stats \
-p 8080:8080 \
-v %h/page-stats/data:/app/data:Z \
localhost/page-stats:latest
ExecStop=/usr/bin/podman stop -t 10 page-stats
[Install]
WantedBy=default.target
EOF
Step 5: Enable and start the service
Reload systemd:
systemctl --user daemon-reload
Enable service to start on boot:
loginctl enable-linger $USER
Start the service:
systemctl --user enable --now page-stats.service
Check status:
systemctl --user status page-stats.service
Stop the service:
systemctl --user stop page-stats.service
Restart the service:
systemctl --user restart page-stats.service
Disable and stop (removes from startup):
systemctl --user disable --now page-stats.service
Step 6: View logs
Follow logs in real-time:
journalctl --user -u page-stats.service -f
View recent logs:
journalctl --user -u page-stats.service -n 50
IMPORTANT
Updating the code: If you modify server.js (e.g., changing the password), you must rebuild the container image and restart the service:
cd ~/page-stats
podman build -t localhost/page-stats:latest .
systemctl --user restart page-stats.service
The container runs a snapshot of your code from when it was built, not the live file.
3) Obtain HTTPS with Caddy (reverse proxy)
Debian/Ubuntu: Install Caddy
Fedora CoreOS: Install Caddy Static Binary
Download and install Caddy:
curl -o caddy 'https://caddyserver.com/api/download?os=linux&arch=amd64'
Make it executable:
chmod +x caddy
Move to system location:
sudo mv caddy /usr/local/bin/
Verify installation:
caddy version
Create Caddy user and group:
sudo groupadd --system caddy
sudo useradd --system --gid caddy --create-home --home-dir /var/lib/caddy --shell /usr/sbin/nologin caddy
Create systemd service:
sudo tee /etc/systemd/system/caddy.service > /dev/null <<'EOF'
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target
[Service]
Type=notify
User=caddy
Group=caddy
ExecStart=/usr/local/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile --force
TimeoutStopSec=5s
LimitNOFILE=1048576
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
EOF
Create log directory
Before configuring Caddy, create the log directory with correct permissions:
sudo mkdir -p /var/log/caddy
sudo chown -R caddy:caddy /var/log/caddy
sudo chmod 755 /var/log/caddy
Generate a bcrypt password hash
Before writing the Caddyfile, generate the hashed password Caddy requires for basic_auth:
caddy hash-password
# Enter your password at the prompt.
# Copy the $2a$14$... string it outputs — you'll paste it into the Caddyfile.
IMPORTANT
Never paste a plain-text password into the Caddyfile. Caddy only accepts bcrypt hashes here.
Configure Caddyfile
Then configure /etc/caddy/Caddyfile:
sudo nano /etc/caddy/Caddyfile
Add the following:
# Replace with your own domain and congratulations you have found my analytics domain ;-)
# Feel free to block it by using uBlock Origin if you don't want me to know you are stalking me
api.michifumi.de {
log {
output file /var/log/caddy/api-access.log {
roll_size 10MB
roll_keep 10
roll_keep_for 720h
}
}
header {
Access-Control-Allow-Origin "https://michifumi.de"
Access-Control-Allow-Methods "GET, POST, OPTIONS, HEAD"
Access-Control-Allow-Headers "Content-Type, Authorization"
Access-Control-Max-Age "86400"
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
}
@options method OPTIONS
handle @options {
respond 204
}
# The only public endpoint: the blog sends beacons to /v1/ping
# (no credentials) and Caddy rewrites it to the app's internal /track route
handle /v1/ping {
rewrite * /track
reverse_proxy localhost:8080
}
# All other endpoints (/summary, /daily, /export) require login
@protected not path /v1/ping
handle @protected {
basic_auth {
# Replace with your own username and the hash from caddy hash-password
admin $2a$14$REPLACE_WITH_YOUR_HASH
}
reverse_proxy localhost:8080
}
}
NOTE
If ports 80/443 are already in use, you can run Caddy on alternate ports, and for a publicly trusted TLS cert on non-443, you typically need DNS-01 validation (see below optional).
Safely updating Caddy configurations
sudo caddy fmt --overwrite /etc/caddy/Caddyfile
sudo -u caddy caddy validate --config /etc/caddy/Caddyfile
IMPORTANT
Run validate as the caddy user, not with plain sudo. Validating opens the log files named in your Caddyfile, and if root does that first, it creates them as root with mode 0600. The running service (which is the caddy user) then cannot open them, and the next systemctl reload caddy fails with open /var/log/caddy/...: permission denied. If that happens, fix the owner with sudo chown caddy:caddy /var/log/caddy/*.log and reload again.
Start the service and check status:
sudo systemctl daemon-reload
sudo systemctl enable --now caddy
sudo systemctl status caddy -l --no-pager
Use reload after the service is running and you make future changes:
sudo systemctl reload caddy
Optional: DNS-01 with Cloudflare (when 80/443 are busy)
If you cannot free ports 80/443, use DNS-01 so Let’s Encrypt validates via DNS. This requires a Caddy build with the Cloudflare DNS module, and your domain’s DNS must be hosted on Cloudflare.
Install Go (latest stable version)
TIP
Visit https://go.dev/dl/ to find the latest stable version. Replace 1.26.6 below with the current version number.
Debian/Ubuntu:
sudo apt remove -y golang-go golang || true
cd /tmp
# Replace 1.26.6 with the latest version from https://go.dev/dl/
curl -LO https://go.dev/dl/go1.26.6.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.26.6.linux-amd64.tar.gz
echo 'export PATH=/usr/local/go/bin:$PATH' | sudo tee /etc/profile.d/go.sh >/dev/null
source /etc/profile.d/go.sh
Fedora CoreOS:
cd /tmp
# Replace 1.26.6 with the latest version from https://go.dev/dl/
curl -LO https://go.dev/dl/go1.26.6.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.26.6.linux-amd64.tar.gz
echo 'export PATH=/usr/local/go/bin:$PATH' | sudo tee /etc/profile.d/go.sh > /dev/null
source /etc/profile.d/go.sh
Verify:
go version
Lock Go to the local toolchain
go env -w GOTOOLCHAIN=local
go env -w GOPROXY=https://proxy.golang.org,direct
Install xcaddy
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
export PATH="$PATH:$HOME/go/bin"
Build Caddy with the Cloudflare DNS module
xcaddy build --with github.com/caddy-dns/cloudflare
Replace the Caddy binary
sudo systemctl stop caddy
sudo install -m 0755 ./caddy /usr/local/bin/caddy
sudo systemctl start caddy
Verify the module exists
caddy list-modules | grep cloudflare
Create a Cloudflare API token with
Zone.Zone:ReadZone.DNS:Edit
Scope it to your zone.
Add the token to the Caddy systemd service
sudo systemctl edit caddy
[Service]
Environment=CLOUDFLARE_API_TOKEN=YOUR_TOKEN_HERE
sudo systemctl daemon-reload
Update the Caddyfile
{
http_port 8081
https_port 8443
}
api.michifumi.de {
tls {
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
}
log {
output file /var/log/caddy/api-access.log {
roll_size 10MB
roll_keep 10
roll_keep_for 720h
}
}
header {
Access-Control-Allow-Origin "https://michifumi.de"
Access-Control-Allow-Methods "GET, POST, OPTIONS, HEAD"
Access-Control-Allow-Headers "Content-Type, Authorization"
Access-Control-Max-Age "86400"
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
}
@options method OPTIONS
handle @options {
respond 204
}
# The only public endpoint: the blog sends beacons to /v1/ping
# (no credentials) and Caddy rewrites it to the app's internal /track route
handle /v1/ping {
rewrite * /track
reverse_proxy localhost:8080
}
# All other endpoints (/summary, /daily, /export) require login
@protected not path /v1/ping
handle @protected {
basic_auth {
admin $2a$14$REPLACE_WITH_YOUR_HASH
}
reverse_proxy localhost:8080
}
}
With https_port 8443 set, access the API at https://api.michifumi.de:8443 and update your tracking endpoint to include :8443.
Validate and reload
sudo caddy fmt --overwrite /etc/caddy/Caddyfile
sudo -u caddy caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
sudo systemctl status caddy -l --no-pager
Confirm issuance
sudo journalctl -u caddy -f
4) DNS
At your DNS provider (I use Dynadot for michifumi.de), add an A record:
- Name:
api - Target: your VM public IP
NOTE
If your DNS is on Cloudflare, set the proxy status to DNS only (gray cloud) until the certificate has been issued.
Make sure the record resolves before you reload Caddy, so the Let’s Encrypt challenge can succeed. Caddy will then fetch the certificate automatically.
After issuance, HTTPS works at https://api.michifumi.de.
5) Add the tracking snippet to the blog (Astro)
Place this near the bottom of your frontend code, such as BaseLayout.astro (before </body>):
<script is:inline>
(() => {
if (typeof window === 'undefined' || typeof navigator === 'undefined') return;
const endpoint = 'https://api.michifumi.de/v1/ping';
const payload = JSON.stringify({
path: window.location.pathname,
referrer: document.referrer || ''
});
try {
if (navigator.sendBeacon) {
const blob = new Blob([payload], { type: 'text/plain' });
const ok = navigator.sendBeacon(endpoint, blob);
if (ok) return;
}
fetch(endpoint, {
method: 'POST',
body: payload,
keepalive: true,
mode: 'no-cors',
headers: { 'Content-Type': 'text/plain' }
}).catch(err => console.warn('[analytics] fetch failed', err));
} catch (err) {
console.warn('[analytics] unexpected error', err);
}
})();
</script>
IMPORTANT
Host the endpoint on a subdomain of your blog’s own domain. uBlock Origin’s default EasyPrivacy list (also the default in Mullvad Browser) contains the rule *$ping,third-party. uBlock Origin documents the ping option as covering navigator.sendBeacon(), so a beacon sent to a different registrable domain than the page is blocked, whatever the hostname or path is. A beacon to api.michifumi.de from michifumi.de is first-party and is not affected by that rule.
This is not a way around opting out: blockers and privacy extensions can still block this endpoint, and visitors who do are simply not counted. See the end of this post for how to block it yourself.
6) Verify end-to-end
From the browser:
- Visit the blog.
The analytics API includes three useful endpoints for viewing detailed statistics:
/daily: Returns daily visit counts per path for the last 30 days. Useful for tracking recent trends over time./summary: Returns all-time totals plus breakdowns by path and by day, suitable for comprehensive dashboard overviews./export: Downloads all raw visit data as CSV for backup or analysis in external tools.
These endpoints make it easy to visualise daily activity or build a simple dashboard.
/daily endpoint
Returns a JSON array with daily stats for each path, sorted by the most recent activity first:
[
{
"path": "/",
"ip": "203.0.113.10",
"views": 15,
"last_seen": "2025-10-31 23:42:07"
},
{
"path": "/blog1",
"ip": "198.51.100.5",
"views": 4,
"last_seen": "2025-10-30 21:15:33"
},
{
"path": "/",
"ip": "203.0.113.10",
"views": 8,
"last_seen": "2025-10-30 18:30:12"
},
{
"path": "/blog2",
"ip": "203.0.113.10",
"views": 3,
"last_seen": "2025-10-30 14:05:44"
}
]
Query it with:
curl -u admin "https://api.michifumi.de/daily"
/summary endpoint
Returns top-level summary stats plus breakdowns:
{
"total_views": 1234,
"unique_paths": 21,
"unique_visitors": 34,
"first_visit": "2025-10-01 09:00:00",
"last_visit": "2025-10-31 11:45:12",
"by_path": [
{ "path": "/", "views": 800 },
{ "path": "/blog1", "views": 120 }
],
"by_day": [
{ "day": "2025-10-31", "views": 45 },
{ "day": "2025-10-30", "views": 38 }
],
"by_ip": [
{ "ip": "203.0.113.10", "views": 650 },
{ "ip": "198.51.100.5", "views": 340 }
]
}
Query it with:
curl -u admin "https://api.michifumi.de/summary"
CSV export:
curl -u admin -L -o stats.csv "https://api.michifumi.de/export"
TIP
All analytics endpoints can be accessed directly from your browser. Caddy will show a native login prompt — enter your admin username and password.
https://api.michifumi.de/dailyhttps://api.michifumi.de/summaryhttps://api.michifumi.de/export(downloads CSV)
7) Data Migration
All analytics live in stats.db. To migrate to a new VM:
Debian/Ubuntu (PM2)
On the old VPS:
pm2 stop stats
# Checkpoint WAL to merge all data into the main database file
sqlite3 ~/page-stats/data/stats.db "PRAGMA wal_checkpoint(TRUNCATE);"
On your local machine:
scp user@OLD_VPS_IP:~/page-stats/data/stats.db ~/Downloads/stats.db
scp ~/Downloads/stats.db user@NEW_VPS_IP:~/page-stats/data/stats.db
On the new VPS:
pm2 start ~/page-stats/server.js --name stats
Fedora CoreOS (Podman)
On the old VPS:
# Stop the service
systemctl --user stop page-stats.service
# Back up the database
mkdir -p ~/backups
cp ~/page-stats/data/stats.db ~/backups/stats.db
On your local machine:
scp user@OLD_VPS_IP:~/backups/stats.db ~/Downloads/stats.db
scp ~/Downloads/stats.db user@NEW_VPS_IP:~/backups/stats.db
On the new VPS:
# Create the data directory and import the database
mkdir -p ~/page-stats/data
cp ~/backups/stats.db ~/page-stats/data/stats.db
# Start the service
systemctl --user start page-stats.service
8) Backup and Data Safety
WARNING
Always maintain regular backups! System updates, hardware failures, or accidental deletions can cause data loss.
Automated CSV Export Backup
Set up a daily backup using the /export endpoint. This works on both Debian/Ubuntu and Fedora CoreOS.
Create a backup script:
mkdir -p ~/backups
nano ~/backups/backup-stats.sh
Add the following content. The script never contains your password: it reads it from the STATS_PASSWORD environment variable, which you provide through cron or systemd (see below), so it never appears in the log file.
#!/bin/bash
# Stop at the first error, so a failed export is not reported as a success
set -euo pipefail
BACKUP_DIR="$HOME/backups/analytics"
mkdir -p "$BACKUP_DIR"
# Export CSV from the analytics endpoint using basic_auth
# STATS_PASSWORD comes from cron or from a systemd EnvironmentFile
curl -fsSL -u "admin:${STATS_PASSWORD}" "https://api.michifumi.de/export" \
-o "$BACKUP_DIR/stats-$(date +%Y-%m-%d).csv"
# Keep only last 30 days of backups
find "$BACKUP_DIR" -name "stats-*.csv" -mtime +30 -delete
echo "Backup completed: $(date)"
Make it executable:
chmod +x ~/backups/backup-stats.sh
Debian/Ubuntu: Schedule with cron (daily at 2 AM):
crontab -e
Add this line:
0 2 * * * STATS_PASSWORD="YOUR_PASSWORD_HERE" /home/YOUR_USERNAME/backups/backup-stats.sh >> /home/YOUR_USERNAME/backups/backup.log 2>&1
Fedora CoreOS: Schedule with systemd timer (daily at 2 AM):
Store the password in a private file instead of the unit file, which is readable by other users. read -s also keeps it out of your shell history:
mkdir -p ~/.config/systemd/user
read -rsp "Admin password: " P; echo
( umask 077; printf 'STATS_PASSWORD=%s\n' "$P" > ~/.config/backup-stats.env )
unset P
ls -l ~/.config/backup-stats.env
The ls output should start with -rw-------.
NOTE
systemd treats backslashes and quotes in environment files specially. If your password contains \, ' or ", quote it as described in man systemd.exec, or pick a password without them.
Create the service unit:
cat > ~/.config/systemd/user/backup-stats.service <<'EOF'
[Unit]
Description=Backup analytics CSV
[Service]
Type=oneshot
EnvironmentFile=%h/.config/backup-stats.env
ExecStart=%h/backups/backup-stats.sh
EOF
Create the timer unit:
cat > ~/.config/systemd/user/backup-stats.timer <<'EOF'
[Unit]
Description=Daily analytics backup
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
Enable and start the timer:
systemctl --user daemon-reload
systemctl --user enable --now backup-stats.timer
Verify the timer is active:
systemctl --user list-timers
Don’t wait until 2 AM to find out whether it works. Run the backup once now:
systemctl --user start backup-stats.service
journalctl --user -u backup-stats.service -n 15 --no-pager
ls -l ~/backups/analytics/
head -n 3 ~/backups/analytics/stats-*.csv
You should see Backup completed in the journal, a dated CSV file, and a header line id,path,referrer,ua,ip,ts followed by real rows. The CSV contains visitor IP addresses, so keep it off shared storage.
WARNING
A failing timer does not alert you. If the script is missing, for example, the unit fails every night and nothing tells you. Check systemctl --user status backup-stats.service after setting it up, and now and then afterwards.
Fedora CoreOS: Backup the Database File
On Fedora CoreOS, the database is stored directly at ~/page-stats/data/stats.db. You can back it up with a simple copy:
# Stop the service
systemctl --user stop page-stats.service
# Copy the database
cp ~/page-stats/data/stats.db ~/backups/stats-$(date +%Y-%m-%d).db
# Start the service
systemctl --user start page-stats.service
Debian/Ubuntu: Direct Database Backup
On Debian/Ubuntu with PM2, use SQLite’s built-in backup command (safe, works while the service is running):
sqlite3 ~/page-stats/data/stats.db ".backup '/home/YOUR_USERNAME/backups/stats-$(date +%Y-%m-%d).db'"
9) Troubleshooting
- “Cannot GET /” when visiting the VM IP: normal — the app only responds to
/track,/summary,/daily, and/export. Through Caddy, the public beacon path is/v1/ping, and everything else asks for a login. - Mixed content blocked: ensure the endpoint is HTTPS and CORS allows your blog origin.
- TLS error (
tlsv1 alert internal error): Caddy has no site block or certificate for that hostname yet. Check that the Caddyfile has the new block, that theapirecord resolves to your VM, and readsudo journalctl -u caddy -f. - DNS check fails: if your DNS is on Cloudflare, gray‑cloud the
apirecord until the certificate is issued. - No data appears: test with a direct
curl -X POST .../v1/ping(through Caddy) or.../track(straight to the app), and checkpm2 logsorjournalctl --user -u page-stats.service. - Backup unit fails with
status=203/EXEC: systemd cannot run the script. It does not exist at~/backups/backup-stats.sh, it is not executable (chmod +x), or the path inExecStart=is wrong. Read the reason withjournalctl --user -u backup-stats.service. - Backup fails with
curl: (22) ... 401: the password in~/.config/backup-stats.env(or in the crontab line) does not match the one behind your Caddybasic_authhash.
Test your endpoint manually
You can manually test your tracking endpoint with:
curl -X POST http://localhost:8080/track \
-H "Content-Type: text/plain" \
-d '{"path":"/hello","referrer":""}'
curl "http://localhost:8080/summary"
A new entry appearing in /summary confirms your app is working correctly. To test the public path through Caddy as well:
curl -i -X POST https://api.michifumi.de/v1/ping \
-H "Content-Type: text/plain" \
-d '{"path":"/caddy-test","referrer":""}'
A 204 No Content response means the beacon was stored. Remember to remove the test row afterwards:
sqlite3 ~/page-stats/data/stats.db "DELETE FROM visits WHERE path = '/caddy-test';"
On Fedora CoreOS, run this inside toolbox enter after sudo dnf install -y sqlite, because the host has no sqlite3 binary.
This blog uses this as a self‑hosted, portable, privacy‑friendly analytics system. If you don’t want me to know you’ve visited my blog (I’d be really sad 😢), you can block it yourself: add ||api.michifumi.de^ under My filters in uBlock Origin, or block the hostname in your DNS or firewall. If you want to build your own, feel free to fork these snippets and adapt the endpoints to your domain.