Open In App

Node.js http.validateHeaderName() Method

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The http.validateHeaderName() (Added in v14.3.0) property is an inbuilt property of the ‘http’ module which performs the low-level validations on the provided name that are done when res.setHeader(name, value) is called. Passing an illegal value as the name will result in a TypeError being thrown, identified by code: “ERR_INVALID_HTTP_TOKEN“.

It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

Note: Use the latest version of Node.js to get the required Output.   

In order to get a response and a proper result, we need to import ‘http’ module.

const http = require('http');

Syntax:

http.validateHeaderName(name);

Parameters: This property accepts a single parameter as mentioned above and described below:

  • name <String>: It accepts the name of the header and it is case-insensitive.

Return Value: It does not return any value, instead validates whether the header is acceptable or not.

The below example illustrates the use of http.validateHeaderName() property in Node.js.

Example 1: Filename: index.js

Javascript




// Node.js program to demonstrate the
// http.validateHeaderName() Method
 
// Importing http module
const http = require('http');
const { validateHeaderName } = require('http');
 
try {
    validateHeaderName('');
} catch (err) {
    err instanceof TypeError; // true
 
    // ERR_INVALID_HTTP_TOKEN
    console.log("Error Occurred", err.code);
 
    // Header name must be a valid
    // HTTP token [""]
    console.log(err.message);
}


Run the index.js file using the following command:

node index.js

Output:

In Console 
>> Error Occurred: 'ERR_INVALID_HTTP_TOKEN' 
>> Header name must be a valid HTTP token [""] 

Example 2: Filename: index.js

Javascript




// Node.js program to demonstrate the
// http.validateHeaderName() Method
 
// Importing http module
const http = require('http');
 
// Another way to import
const { validateHeaderName } = require('http');
 
// Setting up PORT
const PORT = process.env.PORT || 3000;
 
// Creating http Server
const httpServer = http.createServer(
    function (request, response) {
 
        // Setting up Headers
        response.setHeader('Content-Type', 'text/html');
        response.setHeader('Set-Cookie', ['type=ninja',
            'language=javascript']);
 
        // Validating headers
        try {
            validateHeaderName('Content-Type');
            console.log("Header 'Content-Type' Validated True...")
            http.validateHeaderName('set-cookie');
            console.log("Header 'set-cookie' Validated True...")
            http.validateHeaderName('alfa-beta');
            console.log("Header 'alfa-beta' Validated True...")
            validateHeaderName('@@wdjhgw');// not valid
        } catch (err) {
            err instanceof TypeError;
            console.log("Error Occurred", err.code);
 
            // Prints 'Header name must be
            // a valid HTTP token [""]'
            console.log(err.message);
        }
 
        // Getting the set Headers
        const headers = response.getHeaders();
 
        // Printing those headers
        console.log(headers);
 
        // Prints Output on the browser in response
        response.writeHead(200,
            { 'Content-Type': 'text/plain' });
        response.end('ok');
    });
 
// Listening to http Server
httpServer.listen(PORT, () => {
    console.log("Server is running at port 3000...");
});


Run the index.js file using the following command:

node index.js

Output:

In Console 
>> Server is running at port 3000... 
Header 'Content-Type' Validated True... 
Header 'set-cookie' Validated True... 
Header 'alfa-beta' Validated True... 
Error Occurred ERR_INVALID_HTTP_TOKEN 
Header name must be a valid HTTP token ["@@wdjhgw"] 
[Object: null prototype] { 
 'content-type': 'text/html', 
 'set-cookie': [ 'type=ninja', 'language=javascript' ] 
} 

Now run http://localhost:3000/ in the browser.

Output: In Browser 

ok

Reference: https://nodejs.org/api/http.html#http_http_validateheadername_name
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads