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:
- Order of execution: By placing
app.use()at the bottom of the script, Express only executes this function if none of the preceding route handlers matched the requested URL. req.originalUrl: This property captures the exact URL path requested by the client, including query strings.req.method: Captures the HTTP verb (GET, POST, PUT, DELETE, etc.) used for the request.
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
- Avoid Logging Sensitive Data: Ensure you do not log
sensitive headers (like
Authorizationor cookies) or request bodies containing passwords. - Integrate with a Logger: Instead of using standard
console.warn(), send these logs to a production-grade logging utility like Winston or Pino to format them as JSON for easy querying. - Monitor for Security Threats: A sudden spike in
unhandled requests often indicates a vulnerability scanner probing your
application for common endpoints (like
/wp-adminor/.env). Log these events to trigger rate-limiting or IP bans.