HTTP headers carry important information between clients and servers. They describe the content type of a request, authentication details, caching rules, cookies, request identifiers, and many other pieces of metadata. In Node.js applications, headers are often created dynamically using values from configuration files, incoming requests, databases, or external services.
This flexibility also introduces a security and reliability concern. An invalid header name or value can cause an HTTP request or response to fail. More importantly, accepting untrusted header data without proper validation can introduce HTTP response splitting and header injection vulnerabilities.
Node.js provides built-in functions for validating HTTP header names and values through its HTTP module. The validateHeaderName() and validateHeaderValue() functions have been available since Node.js 14.3.0. Newer Node.js releases also provide isValidHeaderName() and isValidHeaderValue(), which return boolean results instead of throwing errors.
This article explains how these functions work, when to use them, and how to apply them when building secure HTTP servers and API clients.
Why HTTP Header Validation Matters
Consider an API that allows clients to provide a custom header name and value. The server receives this information and forwards it to another service.
For example:
const headerName = req.headers['x-custom-header'];
const headerValue = req.headers['x-custom-value'];
res.setHeader(headerName, headerValue);
This example assumes that both values are suitable for use as HTTP headers. In a real application, that assumption may not be correct.
A header name cannot contain arbitrary characters. Similarly, a header value cannot contain characters that violate the HTTP header rules enforced by Node.js.
Consider another example:
res.setHeader('X-User-Name', 'John\nSet-Cookie: admin=true');
The value contains a newline character followed by text that looks like another HTTP header. Node.js rejects invalid header characters instead of allowing this value to be written as a normal response header.
This protection helps prevent applications from accidentally creating malformed HTTP responses or introducing header injection vulnerabilities.
Header validation is particularly important when values come from:
- User-submitted data.
- External APIs.
- Configuration files.
- Database records.
- Proxy headers.
- Custom middleware.
- Dynamically generated authentication or tracing headers.
Understanding HTTP Header Names and Values
Before using Node.js validation functions, it helps to understand the difference between a header name and a header value.
Consider this HTTP request:
GET /api/orders HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer sample-token
X-Request-Id: req-1001
In this request:
- Content-Type is a header name.
- application/json is its value.
- Authorization is a header name.
- Bearer sample-token is its value.
- X-Request-Id is a header name.
- req-1001 is its value.
Header names must follow the HTTP token rules. They cannot contain spaces, control characters, or other characters that are not permitted in an HTTP token.
Header values have different rules. They can contain ordinary text, but certain characters, particularly carriage returns and line feeds, are not allowed in normal HTTP header values.
Node.js provides separate functions because validating a header name and validating its value are two different operations.
Using validateHeaderName() in Node.js
The validateHeaderName() function checks whether a supplied HTTP header name follows the rules used by Node.js when setting response headers.
It is available from the built-in HTTP module.
Its syntax is:
validateHeaderName(name[, label])
The parameters are:
| Parameter | Description |
|---|
| name | Header name that needs validation |
| label | Optional label used in the error message |
The label parameter was added in Node.js 18.14.0 and 19.5.0.
If the supplied header name is invalid, the function throws a TypeError with the error code ERR_INVALID_HTTP_TOKEN.
Basic example
Create a file named validate-header-name.js:
const { validateHeaderName } = require('node:http');
const headers = [
'Content-Type',
'Authorization',
'X-Request-Id',
'bad header',
''
];
for (const name of headers) {
try {
validateHeaderName(name);
console.log(`${name}: Valid`);
} catch (error) {
console.log(`${name}: Invalid`);
console.log(`Error code: ${error.code}`);
}
}
The first three names are valid HTTP header names. The last two are invalid because one contains a space and the other is empty.
A typical output looks like this:
Content-Type: Valid
Authorization: Valid
X-Request-Id: Valid
bad header: Invalid
Error code: ERR_INVALID_HTTP_TOKEN
: Invalid
Error code: ERR_INVALID_HTTP_TOKEN
The function does not return true or false. It either completes successfully or throws an exception.
Using the optional label parameter
The optional label parameter helps produce more descriptive validation errors.
const { validateHeaderName } = require('node:http');
try {
validateHeaderName('invalid header', 'Custom API Header');
} catch (error) {
console.error(error.message);
}
This is useful when an application validates headers from different sources and needs to identify which type of header failed validation.
Using validateHeaderValue() in Node.js
A valid header name does not guarantee that its value is valid.
For example, Content-Type is a valid header name, but a value containing a newline character is not suitable for a normal HTTP response header.
Node.js provides validateHeaderValue() to check header values.
Its syntax is:
validateHeaderValue(name, value)
The function accepts two parameters:
| Parameter | Description |
|---|
| name | Name of the HTTP header |
| value | Value that needs validation |
If the value is invalid, Node.js throws a TypeError.
Two important error codes are:
| Error code | Meaning |
|---|
| ERR_HTTP_INVALID_HEADER_VALUE | The header value is invalid or undefined |
| ERR_INVALID_CHAR | The value contains an invalid character |
Basic example
const { validateHeaderValue } = require('node:http');
const testValues = [
'application/json',
'Bearer sample-token',
'John Smith',
undefined,
'Hello\nWorld'
];
for (const value of testValues) {
try {
validateHeaderValue('X-Custom-Header', value);
console.log('Valid header value:', value);
} catch (error) {
console.log('Invalid header value:', value);
console.log('Error code:', error.code);
}
}
The first three values are valid examples. The undefined value is rejected, and the value containing a newline is rejected because it contains an invalid header character.
Validating a value before setting a response header
You can use validateHeaderValue() before calling setHeader().
const http = require('node:http');
const server = http.createServer((req, res) => {
const headerName = 'X-Application-Version';
const headerValue = '2.5.0';
try {
http.validateHeaderName(headerName);
http.validateHeaderValue(headerName, headerValue);
res.setHeader(headerName, headerValue);
res.end('Header validation successful');
} catch (error) {
res.statusCode = 400;
res.end('Invalid HTTP header');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
This example validates the header before adding it to the response.
However, Node.js already performs header validation when setHeader() is called. Explicit validation is useful when the application needs to check a value earlier, provide a custom error response, or validate multiple headers before writing the response.
Using isValidHeaderName() and isValidHeaderValue()
The exception-based validation functions are useful when invalid input is relatively uncommon. However, applications that frequently receive untrusted header data may prefer a boolean result.
Newer Node.js releases provide two functions for this purpose:
- isValidHeaderName()
- isValidHeaderValue()
Both functions were added in Node.js 26.11.0.
Unlike their validate counterparts, they return true or false instead of throwing an error for invalid input.
Checking header names with isValidHeaderName()
Import the function from the HTTP module:
const { isValidHeaderName } = require('node:http');
console.log(isValidHeaderName('Content-Type'));
console.log(isValidHeaderName('X-Request-Id'));
console.log(isValidHeaderName('bad header'));
console.log(isValidHeaderName(''));
console.log(isValidHeaderName(42));
The output is:
true
true
false
false
false
The function returns false for an empty string, a header name containing a space, and a value that is not a string.
This is useful when an application needs to check a dynamically generated header name without using try-catch for every validation.
Checking header values with isValidHeaderValue()
The isValidHeaderValue() function performs a similar check for header values.
const { isValidHeaderValue } = require('node:http');
console.log(isValidHeaderValue('application/json'));
console.log(isValidHeaderValue('Bearer sample-token'));
console.log(isValidHeaderValue(undefined));
console.log(isValidHeaderValue('Hello\nWorld'));
The output is:
true
true
false
false
The function returns false when the supplied value is invalid.
This makes it convenient for validation logic that needs a simple condition.
For example:
const {
isValidHeaderName,
isValidHeaderValue
} = require('node:http');
function checkHeader(name, value) {
if (!isValidHeaderName(name)) {
return false;
}
if (!isValidHeaderValue(value)) {
return false;
}
return true;
}
console.log(
checkHeader('X-Request-Id', 'req-1001')
);
console.log(
checkHeader('Invalid Header', 'req-1002')
);
The first call returns true, while the second returns false because the header name contains a space.
Understanding Strict and Relaxed Header Value Validation
Newer Node.js releases also provide an httpValidation option for controlling header value validation in supported HTTP APIs.
The option supports strict and relaxed modes for validation.
| Mode | Behavior |
|---|
| strict | Applies the strictest validation and rejects non-ASCII and control characters |
| relaxed | Allows a limited set of non-ASCII and control characters, following Fetch-compatible behavior |
The default validation mode is strict.
The isValidHeaderValue() function accepts an options object containing httpValidation.
For example:
const { isValidHeaderValue } = require('node:http');
const value = 'Hello\u0001World';
console.log(
isValidHeaderValue(value)
);
console.log(
isValidHeaderValue(value, {
httpValidation: 'relaxed'
})
);
Under strict validation, the control character causes the value to be rejected. Relaxed validation permits a limited set of characters that strict mode rejects.
The relaxed mode should not be treated as permission to accept arbitrary user input. It changes the character validation rules, but it does not remove the need for application-level validation.
For most API applications, strict validation is the safer default.
Building a Reusable HTTP Header Validation Function
In a production application, header validation should not be scattered across multiple routes and controllers.
A reusable function makes the validation logic easier to maintain.
The following example uses the newer boolean validation functions available in Node.js 26.11.0 and later.
const {
isValidHeaderName,
isValidHeaderValue
} = require('node:http');
function validateHeaders(headers) {
if (!headers || typeof headers !== 'object') {
return {
valid: false,
message: 'Headers must be an object'
};
}
for (const [name, value] of Object.entries(headers)) {
if (!isValidHeaderName(name)) {
return {
valid: false,
message: `Invalid header name: ${name}`
};
}
if (!isValidHeaderValue(value)) {
return {
valid: false,
message: `Invalid value for header: ${name}`
};
}
}
return {
valid: true,
message: 'All headers are valid'
};
}
const headers = {
'Content-Type': 'application/json',
'X-Request-Id': 'req-1001',
'X-Application-Version': '2.5.0'
};
console.log(validateHeaders(headers));
This function checks every header name and value and returns a descriptive result.
For applications running older Node.js versions, the same approach can be implemented with validateHeaderName() and validateHeaderValue() inside a try-catch block.
One important production consideration is that header validation does not replace header allowlisting. If an application accepts headers from external users, it should define which header names are permitted rather than forwarding every syntactically valid header.
Preventing HTTP Header Injection
HTTP header injection occurs when untrusted input is inserted into an HTTP header without appropriate validation.
One of the risks is HTTP response splitting, where newline characters are used to introduce unexpected header lines or interfere with the structure of a response.
Consider this example:
const http = require('node:http');
const server = http.createServer((req, res) => {
const username = req.url.split('=')[1];
res.setHeader('X-Username', username);
res.end('Request completed');
});
server.listen(3000);
If the username contains invalid characters, Node.js rejects the header when setHeader() is called.
However, relying only on this final validation is not always the best application design. Validate and normalize user input at the application boundary, and use an allowlist when the input controls which headers are created.
For example:
const {
isValidHeaderName,
isValidHeaderValue
} = require('node:http');
function addCustomHeader(res, name, value) {
const allowedHeaders = [
'X-Request-Id',
'X-Application-Version'
];
if (!allowedHeaders.includes(name)) {
throw new Error('Header is not allowed');
}
if (!isValidHeaderName(name)) {
throw new Error('Invalid header name');
}
if (!isValidHeaderValue(value)) {
throw new Error('Invalid header value');
}
res.setHeader(name, value);
}
The allowlist limits which headers can be created. The built-in validation functions then verify that the supplied name and value follow Node.js HTTP header rules.
This is a better approach than accepting arbitrary header names from external input.
validateHeaderName() vs. isValidHeaderName()
Both functions check whether a header name is valid, but they are designed for different validation styles.
| Feature | validateHeaderName() | isValidHeaderName() |
|---|
| Available since | Node.js 14.3.0 | Node.js 26.11.0 |
| Return value | No meaningful value | Boolean |
| Invalid input | Throws TypeError | Returns false |
| Error handling | Requires try-catch | Uses conditional checks |
| Optional label | Supported | Not supported |
| Suitable for | Exception-based validation | Boolean-based validation |
The same distinction applies to validateHeaderValue() and isValidHeaderValue().
If your application supports Node.js 18, 20, 22, or 24, use the validate functions for built-in header validation. Do not assume that the newer boolean functions are available in those releases.
Common Mistakes to Avoid
| Mistake | Why it causes problems | Recommended approach |
|---|
| Validating only header values | An invalid header name can still cause an exception | Validate both names and values |
| Assuming Node.js accepts every string | HTTP headers follow specific character rules | Use the built-in validation functions |
| Passing undefined as a header value | Node.js rejects undefined header values | Check that required values are present |
| Accepting arbitrary header names | Syntactically valid headers may still be inappropriate for the application | Use an allowlist |
| Removing all validation after using setHeader() | Application-specific checks may still be required | Validate data at the application boundary |
| Using newer boolean functions on older Node.js versions | The functions are unavailable before Node.js 26.11.0 | Check the minimum supported runtime version |
| Treating relaxed validation as completely safe | Relaxed mode still has defined restrictions | Prefer strict validation unless compatibility requires otherwise |
| Ignoring error codes | Different failures need different handling | Inspect error.code when using exception-based validation |
Best Practices for Production Node.js Applications
Use Node.js built-in HTTP validation instead of writing custom regular expressions for basic header syntax checks. The built-in functions follow the validation rules used by the HTTP module and reduce the chance of implementing an incomplete validation rule.
Validate dynamic header values before sending them to downstream services. This is particularly important in API gateways, reverse proxies, authentication middleware, and applications that forward incoming request metadata.
Use an allowlist for custom headers. A valid header name is not automatically an authorized header for your application. For example, a service that only needs X-Request-Id and X-Application-Version should not accept arbitrary header names from external clients.
Keep strict header validation as the default. Use relaxed validation only when a specific compatibility requirement justifies it, and understand which characters become acceptable.
Also, avoid logging sensitive header values. Authorization tokens, session cookies, and API credentials should not appear in application logs, even when their header syntax is valid.
Finally, test invalid names, empty values, undefined values, newline characters, and unexpected data types. These cases help identify failures before the application reaches production.
Advantages and Limitations
Node.js provides built-in header validation functions that offer several advantages:
- No additional package is required.
- Header names and values can be checked independently.
- Invalid values produce identifiable error codes when using the validate functions.
- Boolean-based validation is available in newer releases.
- Validation can be integrated into HTTP servers, clients, and middleware.
- Strict and relaxed validation options are available in newer HTTP APIs.
There are also some limitations:
- The newer boolean functions require Node.js 26.11.0 or later.
- The validate functions use exceptions rather than returning validation results.
- Syntax validation does not determine whether a header is appropriate for a particular application.
- Valid headers can still contain sensitive information that should not be logged.
- Header validation alone does not replace authentication, authorization, or input validation.
The best approach is to combine built-in validation with application-specific rules and an allowlist of supported headers.
Summary
Node.js provides validateHeaderName() and validateHeaderValue() for checking HTTP header names and values. These functions have been available since Node.js 14.3.0 and throw TypeError when invalid input is supplied.
Newer Node.js releases also provide isValidHeaderName() and isValidHeaderValue(), introduced in Node.js 26.11.0. They return boolean results, making them convenient for applications that need to check potentially invalid input without relying on exceptions.
For production applications, validate both header names and values, restrict custom headers using an allowlist, and keep strict validation as the default. These practices help prevent malformed HTTP messages and reduce the risk of header injection while making Node.js applications more reliable.
Join the conversation! Your thoughts help the community grow.