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.
29 lines (26 loc) • 1.1 kB
JavaScript
/**
* Function to check if an incoming HTTP request is an AJAX request.
* It inspects the 'x-requested-with' header, which is commonly set by AJAX calls.
*
* @param {Object} req - The HTTP request object, expected to have a 'headers' property.
* @returns {Object} - An object containing the result type, name, and message indicating AJAX detection status.
*/
export default async function checkAjax(req) {
// Retrieve the 'x-requested-with' header from the request headers
const requestedWith = req.headers['x-requested-with'];
// Validate if the request is an AJAX request by comparing the header value to 'XMLHttpRequest'
if (requestedWith !== 'XMLHttpRequest') {
// Return info object when the request is NOT identified as AJAX
return {
type: 'info',
name: 'AJAX',
message: 'Request is not an AJAX call'
};
}
// Return success object when the request is confirmed as AJAX
return {
type: 'success',
name: 'AJAX',
message: 'AJAX request detected'
};
}