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.
82 lines (66 loc) • 2.16 kB
JavaScript
import utils from '../utils/index.js';
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export default async function check(req) {
const results = [];
let userAgent = '';
let ip = '';
// Defensive check to ensure the input is an object to prevent runtime errors.
if (typeof req !== 'object' || req === null) {
return {
status: 'suspicious',
request: {},
details: [{
type: 'error',
name: 'InputValidation',
message: 'Invalid request parameter: expected an object.'
}]
};
}
// Loop through each validator function, invoking with the request.
for (const fn of utils) {
try {
const result = await fn(req);
if (result instanceof NextResponse) {
return result;
}
if (result) {
results.push(result);
// Extract and sanitize User-Agent if present in current result.
if (result.name === 'User-Agent' && result.meta?.['user-agent']) {
userAgent = sanitizeUserAgent(result.meta['user-agent']);
}
// Extract and sanitize IP address if present in current result.
if (result.name === 'IP' && result.meta?.ip) {
ip = sanitizeIp(result.meta.ip);
}
}
} catch (err) {
// Catch and record any errors thrown by individual check functions to avoid breaking the whole process.
results.push({
type: 'error',
name: fn.name || 'UnknownFunction',
message: `Error: ${err.message}`
});
}
}
// Determine overall status based on presence of any errors in results.
const hasError = results.some(r => r.type === 'error');
const status = hasError ? 'suspicious' : 'Completed';
return {
status,
request: {
ip,
'user-agent': userAgent
},
details: results
};
}
function sanitizeUserAgent(ua) {
if (typeof ua !== 'string') return '';
return ua.trim().replace(/[\r\n\t]+/g, ' ');
}
function sanitizeIp(ip) {
if (typeof ip !== 'string') return '';
return ip.trim();
}