This error occurs when you attempt to set an HTTP response status code to a value outside the valid range of 100-599. The HTTP specification requires status codes to be three-digit numbers within this range.
The RangeError with statusCode is thrown by the Node.js HTTP module when your code attempts to set a response status code that violates HTTP specifications. Valid HTTP status codes must be integers between 100 and 599 inclusive. When you call `response.statusCode = value` or `response.writeHead(statusCode, ...)`, Node.js validates that the provided statusCode is within the valid range. If the value is less than 100 or greater than 599, Node.js immediately throws this error. This is a developer error that indicates a logical issue in your code where invalid status codes are being generated or used, which would violate HTTP protocol standards.
Add logging to check what value is being assigned to statusCode:
const statusCode = calculateStatusCode(); // Your logic here
console.log('Status code value:', statusCode, 'Type:', typeof statusCode);
if (statusCode < 100 || statusCode > 599) {
console.error('Invalid status code detected:', statusCode);
}
response.statusCode = statusCode;Check the console output to see what invalid value is being set. This will help identify the source of the problem.
Ensure you only use status codes in the valid range (100-599). Common valid status codes include:
// 1xx Informational
100 // Continue
101 // Switching Protocols
// 2xx Success
200 // OK
201 // Created
204 // No Content
// 3xx Redirection
301 // Moved Permanently
302 // Found
304 // Not Modified
// 4xx Client Error
400 // Bad Request
401 // Unauthorized
403 // Forbidden
404 // Not Found
// 5xx Server Error
500 // Internal Server Error
502 // Bad Gateway
503 // Service UnavailableAlways use one of these standard codes or other valid codes in the 100-599 range.
If your status code is calculated, review the logic to ensure it always produces a valid value:
// WRONG: This could produce invalid values
function getStatusCode(code) {
return code; // Could be anything
}
// CORRECT: Validate and provide defaults
function getStatusCode(code) {
const validCode = Number(code);
if (isNaN(validCode) || validCode < 100 || validCode > 599) {
console.warn('Invalid status code, using 500');
return 500; // Default to server error
}
return validCode;
}
response.statusCode = getStatusCode(someValue);Always validate calculated status codes before using them.
Check for undefined or NaN values that might be used as status codes:
function sendResponse(response, data, statusCode) {
// Validate statusCode is provided and is a number
if (statusCode === undefined || statusCode === null) {
console.warn('statusCode not provided, using 200');
statusCode = 200;
}
if (typeof statusCode !== 'number' || isNaN(statusCode)) {
console.warn('statusCode is not a valid number, using 500');
statusCode = 500;
}
if (statusCode < 100 || statusCode > 599) {
console.warn('statusCode out of range, using 500');
statusCode = 500;
}
response.writeHead(statusCode, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(data));
}This defensive approach prevents invalid status codes from causing crashes.
Create a helper function that maps errors or conditions to valid HTTP status codes:
function getStatusCodeForError(error) {
const statusCodeMap = {
'ValidationError': 400,
'AuthenticationError': 401,
'AuthorizationError': 403,
'NotFoundError': 404,
'ConflictError': 409,
'InternalServerError': 500,
'ServiceUnavailableError': 503,
};
const statusCode = statusCodeMap[error.name] || 500;
return statusCode;
}
// Usage
try {
// Your logic
} catch (error) {
const statusCode = getStatusCodeForError(error);
response.writeHead(statusCode, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ error: error.message }));
}This ensures consistent and valid status code mapping across your application.
Write tests to ensure your code never produces invalid status codes:
const assert = require('assert');
function getResponseStatus(params) {
// Your status code logic
return 200; // Example
}
// Test valid codes
assert(getResponseStatus({}) >= 100 && getResponseStatus({}) <= 599);
assert.strictEqual(getResponseStatus({ error: 'not_found' }), 404);
assert.strictEqual(getResponseStatus({ error: 'unauthorized' }), 401);
// Test error handling
try {
const invalidCode = -1;
if (invalidCode < 100 || invalidCode > 599) {
throw new RangeError(`Invalid status code: ${invalidCode}`);
}
} catch (error) {
assert(error instanceof RangeError);
}
console.log('All status code tests passed');Testing helps catch invalid status code issues during development.
HTTP Status Code Ranges:
The HTTP specification (RFC 7231) defines five status code classes:
- 1xx (100-199): Informational
- 2xx (200-299): Success
- 3xx (300-399): Redirection
- 4xx (400-499): Client Error
- 5xx (500-599): Server Error
Any value outside 100-599 violates the HTTP protocol.
Type Coercion Issues:
Be careful with type coercion. If statusCode comes from user input, a database, or an API, ensure it's parsed to a number correctly:
const statusCode = parseInt(req.query.code, 10); // Parse string to integer
const statusCode = Number(someValue); // Convert to number
const statusCode = +someValue; // Unary plus operatorWithout proper parsing, string values like "500" won't throw an error but will work correctly once converted.
writeHead vs statusCode property:
You can set the status code two ways:
// Method 1: Set statusCode property
response.statusCode = 200;
response.end('OK');
// Method 2: Use writeHead
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('OK');Both methods validate the statusCode and will throw RangeError if invalid.
Express/Web Framework Patterns:
If using Express, use res.status() which abstracts the validation:
app.get('/api/data', (req, res) => {
res.status(200).json({ data: 'value' }); // Safer than direct assignment
});Frameworks like Express and Fastify provide type-safe status code helpers.
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