How to Intercept and Log Unhandled HTTP Requests in Node.js

In modern web development, capturing unexpected traffic is crucial for debugging, monitoring, and security. This article demonstrates how to intercept and log all unhandled HTTP requests in a Node.js backend using both the popular Express.js framework and native Node.js. You will learn how to implement fallback mechanisms that catch unmatched routing paths, log their metadata, and return structured error responses to the client.

Intercepting Unhandled Requests in Express.js

In Express, middleware and routes are executed sequentially in the order they are defined. To intercept unhandled requests, you must place a catch-all middleware function at the very end of your middleware stack, after all legitimate routes have been declared.

Here is how to implement a wildcard fallback middleware:

const express = require('express');
const app = express();

// 1. Define your standard API routes
app.get('/api/users', (req, res) => {
    res.status(200).json({ message: "List of users" });
});

app.post('/api/data', (req, res) => {
    res.status(201).json({ message: "Data received" });
});

// 2. Intercept and log all unhandled requests
app.use((req, res, next) => {
    // Log the request details
    console.warn(`[UNHANDLED REQUEST] ${req.method} ${req.originalUrl} - IP: ${req.ip} - Time: ${new Date().toISOString()}`);

    // Respond with a 404 status
    res.status(404).json({
        error: "Not Found",
        message: `The requested path ${req.originalUrl} does not exist on this server.`,
        method: req.method
    });
});

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

Key Components of the Express Middleware:


Intercepting Unhandled Requests in Native Node.js

If you are building a backend without external frameworks like Express, you handle routing inside Node.js’s native http server module. Unhandled requests are captured by implementing a fallback else statement in your routing conditional logic.

Here is how to set up logging in native Node.js:

const http = require('http');

const server = http.createServer((req, res) => {
    const { method, url } = req;

    // 1. Handle defined routes
    if (url === '/api/users' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: "List of users" }));
    } 
    else if (url === '/api/data' && method === 'POST') {
        res.writeHead(201, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: "Data received" }));
    } 
    // 2. Fallback to intercept and log unhandled requests
    else {
        console.warn(`[UNHANDLED REQUEST] ${method} ${url} - Time: ${new Date().toISOString()}`);

        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
            error: "Not Found",
            message: `The requested path ${url} does not exist on this server.`,
            method: method
        }));
    }
});

server.listen(3000, () => {
    console.log('Native Node.js server running on port 3000');
});

Best Practices for Logging Unhandled Requests