This RangeError occurs when you try to set an HTTP response status code that falls outside the valid range of 100-599. Node.js strictly validates status codes to ensure compliance with HTTP specifications.
This error is thrown by Node.js when you attempt to set an HTTP response status code that doesn't fall within the valid range of 100 to 599 (inclusive). The HTTP specification defines status codes in this range, organized into five classes: 1xx (Informational), 2xx (Success), 3xx (Redirection), 4xx (Client Error), and 5xx (Server Error). Node.js validates the status code whenever you set it using methods like res.statusCode, res.writeHead(), or res.status() in Express. If the value is less than 100, greater than 599, not an integer, or undefined, Node.js throws this RangeError to prevent invalid HTTP responses from being sent to clients. This validation ensures that your application sends well-formed HTTP responses that comply with standards and can be properly interpreted by browsers, proxies, and other HTTP clients.
Check your stack trace to locate the exact line where the error occurs. Look for calls to:
- res.status()
- res.statusCode = ...
- res.writeHead()
- res.sendStatus()
Example error location:
app.get('/api/user', (req, res) => {
const statusCode = undefined; // Problem: undefined
res.status(statusCode).json({ user: data }); // Error thrown here
});If you're using a variable for the status code, make sure it's always set to a valid value. Use default values or validation:
// Bad: status might be undefined
const status = someCondition ? 200 : undefined;
res.status(status).json(data);
// Good: Always provide a valid default
const status = someCondition ? 200 : 500;
res.status(status).json(data);
// Good: Use logical OR for fallback
res.status(status || 200).json(data);Add validation to ensure status codes are integers between 100 and 599:
function isValidStatusCode(code) {
return Number.isInteger(code) && code >= 100 && code <= 599;
}
app.get('/api/data', (req, res) => {
let statusCode = calculateStatus(); // Might return invalid value
if (!isValidStatusCode(statusCode)) {
console.error(`Invalid status code: ${statusCode}`);
statusCode = 500; // Fallback to safe default
}
res.status(statusCode).json({ data });
});Avoid patterns that cause Express to misinterpret numeric values as status codes:
// Bad: Express treats 0 as status code
res.send(0);
// Good: Wrap numeric values in objects or arrays
res.json({ count: 0 });
res.json(0); // Also works with json()
// Bad: Old Express syntax (deprecated)
res.send(200, 'OK');
// Good: Chain status and send
res.status(200).send('OK');
// Bad: Sending multiple arguments
res.send({ id: 1 }, { id: 2 }); // First treated as status
// Good: Send single response
res.json([{ id: 1 }, { id: 2 }]);Error handling middleware often sets dynamic status codes. Ensure they're always valid:
// Robust error handler
app.use((err, req, res, next) => {
// Extract status code safely
let statusCode = err.statusCode || err.status || 500;
// Validate it's in range
if (!Number.isInteger(statusCode) || statusCode < 100 || statusCode > 599) {
console.error(`Invalid error status code: ${statusCode}`);
statusCode = 500;
}
res.status(statusCode).json({
error: err.message,
status: statusCode,
});
});Custom Status Codes: While Node.js restricts status codes to 100-599, the HTTP/1.1 specification (RFC 7231) primarily defines codes in the ranges 100-199, 200-299, 300-399, 400-499, and 500-599. Using undefined status codes (like 299 or 399) is technically valid but may not be understood by clients or proxies.
Fetch API Response Objects: When using the Fetch API or libraries like node-fetch, Response objects have stricter validation. The Fetch specification requires status codes in the range 200-599 for most responses, with even stricter rules for certain response types. This can cause compatibility issues when mocking responses or testing.
TypeScript Type Safety: Use TypeScript with strict typing to catch invalid status codes at compile time:
type HttpStatusCode = 100 | 101 | 200 | 201 | 204 | 301 | 302 | 304 | 400 | 401 | 403 | 404 | 500 | 503;
function setStatus(res: Response, code: HttpStatusCode) {
res.status(code);
}
setStatus(res, 200); // OK
setStatus(res, 999); // Compile errorDebugging Tips: If the source of the invalid status code isn't obvious, add logging before setting status codes:
const originalStatus = res.status.bind(res);
res.status = function(code) {
console.log('Setting status:', code, 'from:', new Error().stack);
return originalStatus(code);
};Third-Party Middleware: Some third-party middleware or libraries might set status codes incorrectly. Review your middleware chain and update or patch problematic packages. Common culprits include outdated error handling libraries and response transformation middleware.
Error: Listener already called (once event already fired)
EventEmitter listener already called with once()
Error: EACCES: permission denied, open '/root/file.txt'
EACCES: permission denied
Error: Invalid encoding specified (stream encoding not supported)
How to fix Invalid encoding error in Node.js readable streams
Error: EINVAL: invalid argument, open
EINVAL: invalid argument, open
TypeError: readableLength must be a positive integer (stream config)
TypeError: readableLength must be a positive integer in Node.js streams