Skip to content

TlsSocket

Defined in: packages/node/src/net/tls-socket.ts:94

TLS socket for establishing encrypted connections to TLS servers.

Unlike TcpSocket, a TLS connection cannot be established on an existing instance: Node.js creates the socket as part of the handshake. The connection therefore starts from the static TlsSocket.connect, which resolves only once the handshake completed and the peer certificate has been verified.

const socket = await TlsSocket.connect(443, { host: "example.com" });

The same method upgrades an already-connected plaintext stream, which is what STARTTLS-style protocols need. The plaintext transport is destroyed if the handshake fails, so a failed upgrade can never fall back to cleartext.

const plain = TcpSocket.from();
await plain.connect(587, { host: "mail.example.com" });
// ... negotiate STARTTLS over the plaintext connection ...
const secure = await TlsSocket.connect(plain.stream, {
servername: "mail.example.com",
});

Accessors that report handshake results (TlsSocket.authorized, TlsSocket.getPeerCertificate, TlsSocket.getCipher, …) are only meaningful once the handshake completed.

new TlsSocket(socket): TlsSocket

Defined in: packages/node/src/net/stream-socket.ts:121

Creates a new StreamSocket instance.

TLSSocket

The underlying Node.js socket.

TlsSocket

InetSocket.constructor

get alpnProtocol(): string | null

Defined in: packages/node/src/net/tls-socket.ts:203

Protocol selected through ALPN, or null before the handshake completed and when no protocol was negotiated.

string | null


get authorizationError(): Error | null

Defined in: packages/node/src/net/tls-socket.ts:195

Reason why the peer certificate was rejected, or null when the peer is authorized or the handshake has not completed yet.

Error | null


get authorized(): boolean

Defined in: packages/node/src/net/tls-socket.ts:187

Whether the peer certificate was signed by one of the configured CAs.

boolean


get bytesRead(): number

Defined in: packages/node/src/net/stream-socket.ts:147

Total number of bytes read from the socket so far.

number

InetSocket.bytesRead


get bytesWritten(): number

Defined in: packages/node/src/net/stream-socket.ts:152

Total number of bytes written to the socket so far.

number

InetSocket.bytesWritten


get closed(): boolean

Defined in: packages/node/src/net/stream-socket.ts:137

Indicates whether the socket has been fully closed.

boolean

InetSocket.closed


get connecting(): boolean

Defined in: packages/node/src/net/stream-socket.ts:157

Whether the socket is currently in the process of connecting.

boolean

InetSocket.connecting


get destroyed(): boolean

Defined in: packages/node/src/net/stream-socket.ts:142

Indicates whether the underlying socket has been destroyed.

boolean

InetSocket.destroyed


get encrypted(): boolean

Defined in: packages/node/src/net/tls-socket.ts:182

Always true; distinguishes a TLS socket from a plaintext one.

boolean


get localEndpoint(): InetEndpoint | null

Defined in: packages/node/src/net/inet-socket.ts:71

Local endpoint of the socket, or null while it is not connected.

If the socket family is not IPv4 or IPv6.

InetEndpoint | null

InetSocket.localEndpoint


get remoteEndpoint(): InetEndpoint | null

Defined in: packages/node/src/net/inet-socket.ts:51

Remote endpoint of the socket, or null while it is not connected.

If the socket family is not IPv4 or IPv6.

InetEndpoint | null

InetSocket.remoteEndpoint


get servername(): string | null

Defined in: packages/node/src/net/tls-socket.ts:213

Server name requested through SNI, or null when the peer sent none.

Only set on sockets accepted by a server.

string | null


get stream(): Duplex

Defined in: packages/node/src/net/stream-socket.ts:132

Underlying duplex stream for reading and writing data.

This is the wrapped net.Socket instance and can be passed directly to APIs that expect a Node.js stream.

Duplex

InetSocket.stream


get timeout(): number | null

Defined in: packages/node/src/net/stream-socket.ts:162

Current inactivity timeout in milliseconds, or null if disabled.

number | null

set timeout(timeout): void

Defined in: packages/node/src/net/stream-socket.ts:173

Updates the inactivity timeout for the socket.

When set to a positive number, the socket emits a “timeout” event if no I/O activity occurs within the given number of milliseconds. A value of 0 or null disables the timeout entirely.

number | null

void

InetSocket.timeout

destroy(): void

Defined in: packages/node/src/net/stream-socket.ts:262

Immediately destroys the underlying socket.

Pending I/O is discarded, the connection is closed and the socket transitions to a terminal state. Any registered “close” listeners will still be invoked.

void

InetSocket.destroy


disableRenegotiation(): void

Defined in: packages/node/src/net/tls-socket.ts:420

Disables renegotiation. Any further renegotiation attempt by the peer emits an error instead.

void


enableTrace(): void

Defined in: packages/node/src/net/tls-socket.ts:425

Enables OpenSSL trace output on standard error, for debugging.

void


end(options?): Promise<void>

Defined in: packages/node/src/net/stream-socket.ts:204

Half-closes the socket, optionally waiting for a full close.

If waitForClose is omitted or false, the promise resolves once the local side has finished sending data and the FIN has been queued. When waitForClose is true, the promise resolves only after the remote side has also closed and the “close” event has fired.

StreamSocketEndOptions

Optional settings for ending the socket.

Promise<void>

A promise that resolves once the socket has ended.

InetSocket.end


exportKeyingMaterial(length, label, context?): Buffer

Defined in: packages/node/src/net/tls-socket.ts:361

Keying material for the connection, as defined by RFC 5705.

number

Number of bytes to derive.

string

Application-specific label.

Buffer<ArrayBufferLike>

Optional application-specific context.

Buffer

The derived keying material.


getCertificate(): PeerCertificate | null

Defined in: packages/node/src/net/tls-socket.ts:223

Returns the local certificate, or null when none was presented.

PeerCertificate | null

The local certificate or null.


getCipher(): CipherNameAndProtocol

Defined in: packages/node/src/net/tls-socket.ts:269

Returns the negotiated cipher suite.

CipherNameAndProtocol

The cipher name, standard name and protocol version.


getEphemeralKeyInfo(): EphemeralKeyInfo | null

Defined in: packages/node/src/net/tls-socket.ts:279

Returns the type, name and size of the ephemeral key exchange, or null when the key exchange was not ephemeral.

EphemeralKeyInfo | null

The ephemeral key information or null.


getFinished(): Buffer<ArrayBufferLike> | null

Defined in: packages/node/src/net/tls-socket.ts:291

Returns the latest Finished message sent to the peer, or null when no handshake completed.

Buffer<ArrayBufferLike> | null

The message or null.


getPeerCertificate(detailed): DetailedPeerCertificate | null

Defined in: packages/node/src/net/tls-socket.ts:236

Returns the peer certificate, or null when the peer presented none.

true

Whether to include the full issuer chain.

DetailedPeerCertificate | null

The peer certificate or null.

getPeerCertificate(detailed?): PeerCertificate | null

Defined in: packages/node/src/net/tls-socket.ts:237

Returns the peer certificate, or null when the peer presented none.

false

Whether to include the full issuer chain.

PeerCertificate | null

The peer certificate or null.


getPeerFinished(): Buffer<ArrayBufferLike> | null

Defined in: packages/node/src/net/tls-socket.ts:301

Returns the latest Finished message received from the peer, or null when no handshake completed.

Buffer<ArrayBufferLike> | null

The message or null.


getPeerX509Certificate(): X509Certificate | null

Defined in: packages/node/src/net/tls-socket.ts:250

Returns the peer certificate as an X509Certificate, or null when the peer presented none.

X509Certificate | null

The peer certificate or null.


getProtocol(): string | null

Defined in: packages/node/src/net/tls-socket.ts:311

Returns the negotiated protocol version, or null before the handshake completed.

string | null

The protocol version such as TLSv1.3, or null.


getSession(): Buffer<ArrayBufferLike> | null

Defined in: packages/node/src/net/tls-socket.ts:321

Returns the negotiated session, which can be passed back as the session connect option to resume it.

Buffer<ArrayBufferLike> | null

The session or null.


getSharedSigalgs(): string[]

Defined in: packages/node/src/net/tls-socket.ts:340

Returns the signature algorithms shared between client and server, in descending order of preference.

string[]

The shared signature algorithms.


getTLSTicket(): Buffer<ArrayBufferLike> | null

Defined in: packages/node/src/net/tls-socket.ts:330

Returns the session ticket, or null when the peer issued none.

Buffer<ArrayBufferLike> | null

The session ticket or null.


getX509Certificate(): X509Certificate | null

Defined in: packages/node/src/net/tls-socket.ts:260

Returns the local certificate as an X509Certificate, or null when none was presented.

X509Certificate | null

The local certificate or null.


isSessionReused(): boolean

Defined in: packages/node/src/net/tls-socket.ts:349

Indicates whether the session was resumed rather than renegotiated.

boolean

true when the session was reused.


isSubscribed<K>(event, listener): boolean

Defined in: packages/async/src/events/event-dispatcher-map-base.ts:38

Check if a callback is subscribed to a specific event.

K extends "connectionAttempt" | "connectionAttemptFailed" | "connectionAttemptTimeout" | "lookup" | keyof StreamSocketEvents | "session" | "secureConnect" | "secure" | "ocspResponse" | "keylog"

K

The event name.

Callable<TlsSocketEvents[K]>

The callback to check.

boolean

InetSocket.isSubscribed


ref(): void

Defined in: packages/node/src/net/stream-socket.ts:181

Marks the socket as referenced, preventing the Node.js process from exiting while the socket is active.

void

InetSocket.ref


renegotiate(options?): Promise<void>

Defined in: packages/node/src/net/tls-socket.ts:378

Renegotiates the TLS session and resolves once the new handshake completed.

TlsSocketRenegotiateOptions

Renegotiation options.

Promise<void>

A promise that resolves once renegotiation completed.

When the socket is already destroyed, since Node.js would never invoke the completion callback.


setKeepAlive(enable, initialDelay?): void

Defined in: packages/node/src/net/inet-socket.ts:93

Sets the keep-alive option for the socket.

boolean

Whether to enable keep-alive.

number

The initial delay in milliseconds before the first keep-alive probe.

void

InetSocket.setKeepAlive


setKeyCert(context): void

Defined in: packages/node/src/net/tls-socket.ts:402

Sets the private key and certificate to use for this socket, overriding the ones inherited from the secure context.

TlsSecureContext

The secure context or the options to build one from.

void


setMaxSendFragment(size): boolean

Defined in: packages/node/src/net/tls-socket.ts:412

Sets the maximum TLS fragment size.

number

The maximum fragment size, between 512 and 16384.

boolean

true when the limit was set.


setNoDelay(noDelay): void

Defined in: packages/node/src/net/inet-socket.ts:102

Enables or disables the Nagle algorithm for the socket.

boolean

Whether to disable the Nagle algorithm.

void

InetSocket.setNoDelay


subscribe<K>(event, listener, options?): Callable | null

Defined in: packages/async/src/events/event-dispatcher-map-base.ts:23

K extends "connectionAttempt" | "connectionAttemptFailed" | "connectionAttemptTimeout" | "lookup" | keyof StreamSocketEvents | "session" | "secureConnect" | "secure" | "ocspResponse" | "keylog"

K

Callable<TlsSocketEvents[K]>

EventDispatcherSubscribeOptions

Callable | null

InetSocket.subscribe


unref(): void

Defined in: packages/node/src/net/stream-socket.ts:189

Marks the socket as unreferenced, allowing the Node.js process to exit even if the socket is still active.

void

InetSocket.unref


unsubscribe<K>(event, listener): void

Defined in: packages/async/src/events/event-dispatcher-map-base.ts:31

Unsubscribe a callback from a specific event.

K extends "connectionAttempt" | "connectionAttemptFailed" | "connectionAttemptTimeout" | "lookup" | keyof StreamSocketEvents | "session" | "secureConnect" | "secure" | "ocspResponse" | "keylog"

K

The event name.

Callable<TlsSocketEvents[K]>

The callback to remove.

void

InetSocket.unsubscribe


wait<K>(event, options?): Promise<TlsSocketEvents[K]>

Defined in: packages/async/src/events/event-dispatcher-map-base.ts:45

Wait for the next occurrence of a specific event, optionally matching a predicate.

This is a convenience method that subscribes to the dispatcher, waits for the next event that matches the predicate (if provided), and then unsubscribes automatically.

K extends "connectionAttempt" | "connectionAttemptFailed" | "connectionAttemptTimeout" | "lookup" | keyof StreamSocketEvents | "session" | "secureConnect" | "secure" | "ocspResponse" | "keylog"

K

The event name to wait for.

EventDispatcherWaitOptions<TlsSocketEvents[K]>

Optional settings including predicate and abort signal.

Promise<TlsSocketEvents[K]>

A promise that resolves with the event arguments as an array.

InetSocket.wait


write(data): Promise<void>

Defined in: packages/node/src/net/stream-socket.ts:241

Writes data to the socket and resolves once that chunk has been flushed.

Awaiting the result is what applies backpressure: the promise settles on the chunk’s own flush rather than on the whole buffer draining, so a producer that awaits each write never outruns the socket. A caller that does not await is free to queue without bound.

Uint8Array

The data to write.

Promise<void>

When the socket errors or is destroyed before the chunk flushes.

InetSocket.write


static connect(port, options?): Promise<TlsSocket>

Defined in: packages/node/src/net/tls-socket.ts:119

Connects to a TLS server and resolves once the handshake completed.

number

The port to connect to.

TlsSocketConnectOptions

Connection options, including the host, the secure context and an optional abort signal.

Promise<TlsSocket>

A promise that resolves with the connected socket.

static connect(path, options?): Promise<TlsSocket>

Defined in: packages/node/src/net/tls-socket.ts:133

Connects to a TLS server listening on a local endpoint and resolves once the handshake completed.

string

Filesystem path of the Unix domain socket, or the name of the Windows named pipe.

TlsSocketConnectOptions

Connection options, including the secure context and an optional abort signal.

Promise<TlsSocket>

A promise that resolves with the connected socket.

static connect(stream, options?): Promise<TlsSocket>

Defined in: packages/node/src/net/tls-socket.ts:146

Upgrades an already-connected stream to TLS and resolves once the handshake completed.

Duplex

The plaintext stream to encrypt.

TlsSocketConnectOptions

Connection options, including the secure context and an optional abort signal.

Promise<TlsSocket>

A promise that resolves with the secured socket.


static from(stream, options?): TlsSocket

Defined in: packages/node/src/net/tls-socket.ts:107

Wraps an existing stream in a TLS socket without waiting for the handshake.

The handshake starts immediately and its outcome is reported through the TlsSocketEvents.secureConnect and StreamSocketEvents.error events. Prefer TlsSocket.connect, which reports both through the returned promise; use this method only to drive the handshake manually.

Duplex

The plaintext stream to encrypt.

Options for the underlying Node.js TLS socket.

boolean

Treat intermediate (non-self-signed) certificates in the trust CA certificate list as trusted.

Since

v22.9.0, v20.18.0

(arg) => string | undefined

If set, this will be called when a client opens a connection using the ALPN extension. One argument will be passed to the callback: an object containing servername and protocols fields, respectively containing the server name from the SNI extension (if any) and an array of ALPN protocol name strings. The callback must return either one of the strings listed in protocols, which will be returned to the client as the selected ALPN protocol, or undefined, to reject the connection with a fatal alert. If a string is returned that does not match one of the client’s ALPN protocols, an error will be thrown. This option cannot be used with the ALPNProtocols option, and setting both options will throw an error.

ArrayBufferView<ArrayBufferLike> | readonly string[]

An array of strings, or a single Buffer, TypedArray, or DataView containing the supported ALPN protocols. Buffers should have the format [len][name][len][name]... e.g. '\x08http/1.1\x08http/1.0', where the len byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. ['http/1.1', 'http/1.0']. Protocols earlier in the list have higher preference than those later.

string | Buffer<ArrayBufferLike> | (string | Buffer<ArrayBufferLike>)[]

Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla’s CAs are completely replaced when CAs are explicitly specified using this option.

string | Buffer<ArrayBufferLike> | (string | Buffer<ArrayBufferLike>)[]

Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.

readonly CertificateCompressionAlgorithm[]

An array of supported certificate compression algorithm names, in preference order. Supported values are 'zlib', 'brotli', and 'zstd'. When set, enables TLS certificate compression (RFC 8879) which compresses certificates during the TLS handshake, reducing handshake size. Only effective with TLSv1.3. Default: [] (disabled).

string

Cipher suite specification, replacing the default. For more information, see modifying the default cipher suite. Permitted ciphers can be obtained via tls.getCiphers(). Cipher names must be uppercased in order for OpenSSL to accept them.

string

Name of an OpenSSL engine which can provide the client certificate.

Deprecated

string | Buffer<ArrayBufferLike> | (string | Buffer<ArrayBufferLike>)[]

PEM formatted CRLs (Certificate Revocation Lists).

string | Buffer<ArrayBufferLike>

'auto' or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. ECDHE-based perfect forward secrecy will still be available.

string

A string describing a named curve, TLS group, or colon-separated list of named curves or TLS groups to use for key agreement, for example P-521:P-384:P-256, X25519, or X25519MLKEM768. The historical name of this option refers to ECDH key agreement in TLSv1.2 and below. In TLSv1.3, this option configures the TLS Supported Groups and key share groups offered or accepted by the TLS stack. Set to auto to select the group automatically. Use crypto.getCurves() to obtain a list of available elliptic curve names. For TLS group names, use openssl list -tls-groups or consult the IANA TLS Supported Groups registry.

boolean

When enabled, TLS packet trace information is written to stderr. This can be used to debug TLS connection problems.

Default

false

boolean

Attempt to use the server’s cipher suite preferences instead of the client’s. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions

string | Buffer<ArrayBufferLike> | (string | Buffer<ArrayBufferLike> | KeyObject)[]

Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: ]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.

SecureVersion

Optionally set the maximum TLS version to allow. One of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified along with the secureProtocol option, use one or the other. Default: 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to 'TLSv1.3'. If multiple of the options are provided, the highest maximum is used.

SecureVersion

Optionally set the minimum TLS version to allow. One of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified along with the secureProtocol option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability. Default: 'TLSv1.2', unless changed using CLI options. Using --tls-v1.0 sets the default to 'TLSv1'. Using --tls-v1.1 sets the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to ‘TLSv1.3’. If multiple of the options are provided, the lowest minimum is used.

string

Shared passphrase used for a single private key and/or a PFX.

string | Buffer<ArrayBufferLike> | (string | Buffer<ArrayBufferLike> | PxfObject)[]

PFX or PKCS12 encoded private key and certificate chain. pfx is an alternative to providing key and cert individually. PFX is usually encrypted, if it is, passphrase will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form {buf: <string|buffer>[, passphrase: ]}. The object form can only occur in an array. object.passphrase is optional. Encrypted PFX will be decrypted with object.passphrase if provided, or options.passphrase if it is not.

string

Name of an OpenSSL engine to get private key from. Should be used together with privateKeyIdentifier.

Deprecated

string

Identifier of a private key managed by an OpenSSL engine. Should be used together with privateKeyEngine. Should not be set together with key, because both options define a private key in different ways.

Deprecated

boolean

If true the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if requestCert is true.

Default

true

boolean

If true the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to false.

boolean

If true, specifies that the OCSP status request extension will be added to the client hello and an ‘OCSPResponse’ event will be emitted on the socket before establishing a secure communication.

SecureContext

An optional TLS context object from tls.createSecureContext()

number

Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options

string

Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use minVersion and maxVersion instead. The possible values are listed as SSL_METHODS, use the function names as strings. For example, use ‘TLSv1_1_method’ to force TLS version 1.1, or ‘TLS_method’ to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. Default: none, see minVersion.

Buffer<ArrayBufferLike>

An optional Buffer instance containing a TLS session.

string

Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.

number

The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default: 300.

string

Colon-separated list of supported signature algorithms. The list can contain digest algorithms (SHA256, MD5 etc.), public key algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g ‘RSA+SHA384’) or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).

(servername, cb) => void

SNICallback(servername, cb) A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: servername and cb. SNICallback should invoke cb(null, ctx), where ctx is a SecureContext instance. (tls.createSecureContext(…) can be used to get a proper SecureContext.) If SNICallback wasn’t provided the default callback with high-level API will be used (see below).

Buffer<ArrayBufferLike>

48-bytes of cryptographically strong pseudo-random data. See Session Resumption for more information.

TlsSocket

A new TlsSocket instance whose handshake is in progress.

InetSocket.from