Invalid protocol specified for the request
Production Risk
Low — caught immediately; use the fetch API or a URL-aware library to avoid this entirely.
Thrown when the protocol option provided to http.request() or https.request() does not match the module being used. For example, specifying protocol: "https:" in an http.request() call, or vice versa.
- 1Using https: protocol with the http module
- 2Using http: protocol with the https module
- 3Dynamically building request options with the wrong protocol string
Triggered when the HTTP/HTTPS request options are validated and the protocol does not match.
const http = require('http');
http.request({
hostname: 'example.com',
protocol: 'https:', // wrong for http module
});expected output
Error [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"
Fix 1
Match the protocol option to the module used
WHEN When setting protocol explicitly in request options
const https = require('https');
https.request({
hostname: 'example.com',
protocol: 'https:', // correct for https module
path: '/',
});Why this works
Using the correct module-protocol pairing satisfies the validation check.
Fix 2
Parse the URL and choose the correct module automatically
WHEN When the URL is dynamic
const url = new URL('https://example.com/api');
const mod = url.protocol === 'https:' ? require('https') : require('http');
mod.request(url);Why this works
Selecting the module based on the URL protocol guarantees they always match.
const http = require('http');
http.request({
hostname: 'example.com',
protocol: 'https:', // wrong for http module
}); // this triggers ERR_INVALID_PROTOCOLtry {
// operation that may throw ERR_INVALID_PROTOCOL
riskyOperation()
} catch (err) {
if (err.code === 'ERR_INVALID_PROTOCOL') {
console.error('ERR_INVALID_PROTOCOL:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_invalid_protocol(...args) {
// validate args here
return performOperation(...args)
}✕ Mix http and https modules with mismatched protocol options
The modules are protocol-specific; mismatching causes an immediate validation error.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev