Categories We Write About

Build a website error logger

Here’s a simple implementation of a website error logger using JavaScript (frontend) and Node.js with Express (backend). This logger captures JavaScript errors on the client side and sends them to a backend API for logging.


Frontend: Capture JavaScript Errors

Place this script inside your HTML <head> or at the end of the <body>:

html
<script> window.onerror = function (message, source, lineno, colno, error) { const errorData = { message, source, lineno, colno, stack: error?.stack || null, userAgent: navigator.userAgent, timestamp: new Date().toISOString(), }; fetch('/log-error', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(errorData), }); }; </script>

Backend: Node.js with Express

Set up a simple Express server to receive and log errors.

Install dependencies:

bash
npm init -y npm install express

server.js:

javascript
const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = 3000; app.use(express.json()); app.post('/log-error', (req, res) => { const errorLog = req.body; const logEntry = `${errorLog.timestamp} | ${errorLog.message} | ${errorLog.source}:${errorLog.lineno}:${errorLog.colno}nStack: ${errorLog.stack}nUserAgent: ${errorLog.userAgent}nn`; fs.appendFile(path.join(__dirname, 'error_logs.txt'), logEntry, (err) => { if (err) { console.error('Error writing to log file:', err); return res.status(500).send('Logging failed'); } res.status(200).send('Error logged'); }); }); app.listen(PORT, () => { console.log(`Error logger running on http://localhost:${PORT}`); });

Optional: Log Viewer (Admin Interface)

You can add a route to view logged errors in the browser:

javascript
app.get('/view-logs', (req, res) => { fs.readFile(path.join(__dirname, 'error_logs.txt'), 'utf8', (err, data) => { if (err) return res.status(500).send('Could not read logs'); res.type('text/plain').send(data); }); });

Security Tips

  • Restrict /log-error to accept requests only from your domain.

  • Protect /view-logs behind authentication in production.

  • Rate limit to prevent abuse.


This basic error logger provides a lightweight yet powerful solution to monitor JavaScript errors on your website. You can expand it to include email alerts, integration with tools like Slack or Discord, or even use a real-time database for querying error stats.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About