How to fix RangeError: The value of 'statusCode' is out of range. It must be >= 100 and <= 599. in Node.js

Node.jsBEGINNERMEDIUMUpdated Dec 9, 2025ยท 200 views

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.

Quick fix

Fixes RangeError

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;
  1. Verify the status code value
  2. Use valid HTTP status codes
  3. Fix arithmetic or logic errors
  4. Handle undefined or NaN values
node.js โ€” error
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;
RangeError: The value of 'statusCode' is out of range. It must be >= 100 and <= 599.

What this error means

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.

Typical symptoms

  • Application crashes when trying to send a response with an invalid status code
  • RangeError thrown immediately when setting response.statusCode
  • Error message specifies the invalid statusCode value
  • Response is never sent to the client before the crash
  • Stack trace points to response.statusCode assignment or writeHead() call
  • Error occurs during request handling, not during server startup

Common causes

  1. Explicitly setting response.statusCode to a value less than 100 or greater than 599
  2. Passing an invalid statusCode to response.writeHead()
  3. Using a negative number or zero as a status code
  4. Using a number greater than 599 as a status code
  5. Status code is the result of invalid arithmetic or calculation
  6. Conditional logic produces invalid status codes
  7. Undefined or NaN value is being used as the status code
  8. Type coercion from a string or other type results in an invalid number

How to fix "RangeError: The value of 'statusCode' is out of range. It must be >= 100 and <= 599."

1Verify the status code value

Add logging to check what value is being assigned to statusCode:

javascript
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.

2Use valid HTTP status codes

Ensure you only use status codes in the valid range (100-599). Common valid status codes include:

javascript
// 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 Unavailable

Always use one of these standard codes or other valid codes in the 100-599 range.

3Fix arithmetic or logic errors

If your status code is calculated, review the logic to ensure it always produces a valid value:

javascript
// 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.

4Handle undefined or NaN values

Check for undefined or NaN values that might be used as status codes:

javascript
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.

5Use a status code mapping function

Create a helper function that maps errors or conditions to valid HTTP status codes:

javascript
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.

6Test status code boundaries

Write tests to ensure your code never produces invalid status codes:

javascript
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.

Advanced notes

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:

javascript
const statusCode = parseInt(req.query.code, 10); // Parse string to integer
const statusCode = Number(someValue);            // Convert to number
const statusCode = +someValue;                   // Unary plus operator

Without 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:

javascript
// 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:

javascript
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.

Frequently asked questions

What does "RangeError" mean?
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. js validates that the provided statusCode is within the valid range.
How do I fix "RangeError"?
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.
What causes "RangeError"?
Explicitly setting response.statusCode to a value less than 100 or greater than 599 Passing an invalid statusCode to response.writeHead() Using a negative number or zero as a status code
Is the "RangeError" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading