header-middleware-next
Version:
A lightweight and flexible middleware utility for managing HTTP headers in Next.js applications. Supports header extraction, transformation, masking, and safe injection for Edge and API routes.
45 lines (42 loc) • 1.76 kB
JavaScript
/**
* Function to extract and verify the client's IP address from an incoming HTTP request.
* It attempts to determine the IP by checking multiple standard headers and connection properties,
* accounting for common proxy forwarding and network configurations.
*
* @param {Object} req - The HTTP request object containing headers and connection information.
* @returns {Object} - An object representing the detection result, including status type, name, message, and meta information with the IP.
*/
export default async function checkIP(req) {
/**
* Attempt to retrieve the client's IP address using multiple fallbacks:
* 1. 'x-forwarded-for' header - may contain a list of IPs when behind proxies; use the first IP.
* 2. req.ip - commonly set by frameworks like Express.
* 3. req.connection.remoteAddress - legacy Node.js property for remote IP.
* 4. req.socket.remoteAddress - socket-level IP address.
* 5. req.connection.socket.remoteAddress - additional legacy fallback.
* If none are available, default to an empty string.
*/
let ip =
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
req.ip ||
req.connection?.remoteAddress ||
req.socket?.remoteAddress ||
req.connection?.socket?.remoteAddress ||
'';
// If no IP address could be resolved, return a warning with empty meta IP.
if (!ip) {
return {
type: 'warning',
name: 'IP',
message: 'IP address could not be determined',
meta: { ip: '' }
};
}
// On successful IP detection, return a success type with the resolved IP in the message and meta.
return {
type: 'success',
name: 'IP',
message: `IP detected: ${ip}`,
meta: { ip }
};
}