Differentiate error responses
Return JSON-shaped failures for requests that identify themselves as XMLHttpRequest requests.
Express.js · Pipe
req.xhr is a Boolean request property that indicates whether the X-Requested-With header is XMLHttpRequest. Use it to choose handling for requests identifying themselves as XMLHttpRequest requests.
req.xhr is a read-only Boolean-style request property. Express derives it from the incoming X-Requested-With header, allowing middleware or handlers to distinguish requests identifying themselves as XMLHttpRequest requests from other HTTP requests.
req.xhrBoolean
XMLHttpRequest for the property to be true.const express = require('express');
const app = express();
app.use((err, req, res, next) => {
if (req.xhr) {
res.status(500).send({ error: 'Request failed' });
} else {
next(err);
}
});
app.get('/', (req, res) => res.send('ok'));
app.listen(3000);Run the app, then send a request with X-Requested-With: XMLHttpRequest to exercise the JSON error branch.
Return JSON-shaped failures for requests that identify themselves as XMLHttpRequest requests.
Select a compact or interactive response path based on the request’s declared client style.
Inspect client-request metadata while developing or troubleshooting middleware behavior.
req.xhr indicate?req.xhr is a Boolean property that is true when the request’s X-Requested-With header equals XMLHttpRequest. It can be used to select a response format or error-handling path.
Follow-up: How would you avoid trusting it for authorization? Treat it only as a presentation hint and enforce authorization independently with authenticated identity and server-side permission checks.
Express checks the incoming X-Requested-With header and exposes the result through req.xhr. A client library such as jQuery commonly sends the identifying header.
Follow-up: What should a client do if it needs this branch? Explicitly send X-Requested-With: XMLHttpRequest, while recognizing that intermediaries or client behavior may omit it.
req.xhr be used in error handling?A middleware can branch on req.xhr, send a compact structured error for that request type, or call next(err) to let another error handler process it. The property is useful for choosing presentation, not for changing core request semantics.
Follow-up: How can an error handler preserve normal behavior for non-XHR requests? Handle the XHR case locally and delegate all other errors with next(err).
reqreq.get()req.headersapp.use()