TLS context is not a valid SecureContext
Production Risk
Causes TLS server to fail during handshake for SNI-served hostnames.
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.
- 1Passing a plain options object to SNICallback instead of a SecureContext
- 2Returning undefined from SNICallback where a SecureContext is expected
- 3Passing the result of the wrong API to context-accepting parameters
Triggered when a TLS API receives a value that should be a SecureContext but is not.
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
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.
const tls = require('tls');
const server = tls.createServer({
SNICallback: (servername, cb) => {
cb(null, { cert: '...', key: '...' }); // wrong — needs SecureContext
},
}); // this triggers ERR_TLS_INVALID_CONTEXTtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_tls_invalid_context(...args) {
// validate args here
return performOperation(...args)
}✕ Pass raw options objects where a SecureContext is required
The TLS stack requires a compiled SecureContext; plain objects are not equivalent.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev