ERR_INVALID_PROTOCOL
Node.jsERRORNotableNetworkHIGH confidence

Invalid protocol specified for the request

Production Risk

Low — caught immediately; use the fetch API or a URL-aware library to avoid this entirely.

What this means

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.

Why it happens
  1. 1Using https: protocol with the http module
  2. 2Using http: protocol with the https module
  3. 3Dynamically building request options with the wrong protocol string
How to reproduce

Triggered when the HTTP/HTTPS request options are validated and the protocol does not match.

trigger — this will error
trigger — this will error
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

Match the protocol option to the module used
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

Parse the URL and choose the correct module automatically
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.

Code examples
Triggerjs
const http = require('http');
http.request({
  hostname: 'example.com',
  protocol: 'https:', // wrong for http module
});  // this triggers ERR_INVALID_PROTOCOL
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_invalid_protocol(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Mix http and https modules with mismatched protocol options

The modules are protocol-specific; mismatching causes an immediate validation error.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors