Node.js Integration

Integrate error tracking into your Node.js applications

Express.js Integration

1. Install Dependencies

npm install axios

2. Create Error Logger Module

// errorLogger.js
const axios = require('axios');

const API_KEY = process.env.ERROR_LOG_API_KEY || 'YOUR_API_KEY';
const SECURITY_KEY = process.env.ERROR_LOG_SECURITY_KEY || 'YOUR_SECURITY_KEY';
const WEBHOOK_URL = `https://your-domain.com/api/ingest/${API_KEY}`;

async function logError(error, additionalInfo = {}) {
    try {
        await axios.post(WEBHOOK_URL, {
            message: error.message,
            stackTrace: error.stack,
            ...additionalInfo
        }, {
            headers: {
                'Content-Type': 'application/json',
                'X-Security-Key': SECURITY_KEY
            }
        });
    } catch (err) {
        // Silently fail - don't let error logging crash your app
        console.error('Failed to log error:', err.message);
    }
}

module.exports = { logError };

3. Express Error Middleware

// app.js
const express = require('express');
const { logError } = require('./errorLogger');

const app = express();

// Your routes here...

// Error handling middleware (must be last)
app.use((err, req, res, next) => {
    // Log to ErrorLogDashboard
    logError(err, {
        url: req.url,
        method: req.method,
        ip: req.ip
    });

    // Send response to client
    res.status(500).json({ error: 'Internal server error' });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

4. Manual Error Logging

const { logError } = require('./errorLogger');

app.get('/api/users/:id', async (req, res) => {
    try {
        const user = await getUserById(req.params.id);
        res.json(user);
    } catch (error) {
        await logError(error, {
            userId: req.params.id,
            action: 'get_user'
        });
        res.status(500).json({ error: 'Failed to fetch user' });
    }
});

Next.js Integration

// pages/api/error-handler.js
import axios from 'axios';

export async function logError(error, context = {}) {
    const API_KEY = process.env.ERROR_LOG_API_KEY;
    const SECURITY_KEY = process.env.ERROR_LOG_SECURITY_KEY;
    
    try {
        await axios.post(
            `https://your-domain.com/api/ingest/${API_KEY}`,
            {
                message: error.message,
                stackTrace: error.stack,
                context
            },
            {
                headers: {
                    'X-Security-Key': SECURITY_KEY
                }
            }
        );
    } catch (err) {
        console.error('Error logging failed:', err);
    }
}

// Use in API routes:
export default async function handler(req, res) {
    try {
        // Your code
    } catch (error) {
        await logError(error, { route: req.url });
        res.status(500).json({ error: 'Internal error' });
    }
}

Process-Level Error Handling

const { logError } = require('./errorLogger');

// Catch unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
    logError(new Error(`Unhandled Rejection: ${reason}`));
});

// Catch uncaught exceptions
process.on('uncaughtException', (error) => {
    logError(error);
    // Gracefully shutdown
    process.exit(1);
});

Environment Variables: Store your keys in .env file and add it to .gitignore!