ERR_TLS_INVALID_CONTEXT
Node.jsERRORNotableTLSHIGH confidence

TLS context is not a valid SecureContext

Production Risk

Causes TLS server to fail during handshake for SNI-served hostnames.

What this means

Thrown when a value passed as a TLS secure context is not a valid tls.SecureContext object. Functions like tls.createSecureContext() return a SecureContext that must be used as-is; passing a raw options object or other value is not permitted.

Why it happens
  1. 1Passing a plain options object to SNICallback instead of a SecureContext
  2. 2Returning undefined from SNICallback where a SecureContext is expected
  3. 3Passing the result of the wrong API to context-accepting parameters
How to reproduce

Triggered when a TLS API receives a value that should be a SecureContext but is not.

trigger — this will error
trigger — this will error
const tls = require('tls');
const server = tls.createServer({
  SNICallback: (servername, cb) => {
    cb(null, { cert: '...', key: '...' }); // wrong — needs SecureContext
  },
});

expected output

TypeError [ERR_TLS_INVALID_CONTEXT]: context must be a SecureContext

Fix

Create a SecureContext with tls.createSecureContext()

WHEN In SNICallback or any context-accepting TLS API

Create a SecureContext with tls.createSecureContext()
const tls = require('tls');
const fs = require('fs');
const ctx = tls.createSecureContext({
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem'),
});
const server = tls.createServer({
  SNICallback: (servername, cb) => cb(null, ctx),
});

Why this works

tls.createSecureContext() produces a proper SecureContext that satisfies the type check.

Code examples
Triggerjs
const tls = require('tls');
const server = tls.createServer({
  SNICallback: (servername, cb) => {
    cb(null, { cert: '...', key: '...' }); // wrong — needs SecureContext
  },
});  // this triggers ERR_TLS_INVALID_CONTEXT
Handle in try/catchjs
try {
  // operation that may throw ERR_TLS_INVALID_CONTEXT
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_TLS_INVALID_CONTEXT') {
    console.error('ERR_TLS_INVALID_CONTEXT:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_tls_invalid_context(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Pass raw options objects where a SecureContext is required

The TLS stack requires a compiled SecureContext; plain objects are not equivalent.

Same error in other languages
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