Network Error Logging (NEL)

Network Error Logging (NEL)

Implementing Network Error Logging

class NetworkErrorLogging {
    constructor() {
        this.config = {
            reportTo: 'network-errors',
            maxAge: 86400,
            includeSubdomains: true
        };
    }
    
    middleware() {
        return (req, res, next) => {
            // Configure Report-To header
            res.setHeader('Report-To', JSON.stringify({
                group: 'network-errors',
                max_age: this.config.maxAge,
                endpoints: [{
                    url: 'https://reporting.example.com/nel'
                }],
                include_subdomains: this.config.includeSubdomains
            }));
            
            // Configure NEL header
            res.setHeader('NEL', JSON.stringify({
                report_to: this.config.reportTo,
                max_age: this.config.maxAge,
                include_subdomains: this.config.includeSubdomains,
                failure_fraction: 0.1, // Report 10% of failures
                success_fraction: 0.01  // Report 1% of successes
            }));
            
            next();
        };
    }
    
    // Process NEL reports
    handleNELReports() {
        return async (req, res) => {
            const reports = req.body;
            
            for (const report of reports) {
                if (report.type === 'network-error') {
                    await this.processNetworkError(report);
                }
            }
            
            res.status(204).end();
        };
    }
    
    async processNetworkError(report) {
        const error = {
            timestamp: new Date(report.age),
            type: report.body.type,
            url: report.body.url,
            status: report.body.status_code,
            elapsed: report.body.elapsed_time,
            method: report.body.method,
            phase: report.body.phase
        };
        
        // Analyze patterns
        if (error.status === 0) {
            console.error('Network failure detected:', error);
        } else if (error.status >= 500) {
            console.error('Server error detected:', error);
        }
        
        // Store for analysis
        await this.storeError(error);
    }
}