When two backend services communicate over HTTPS, the server normally proves its identity using a TLS certificate. The client verifies that certificate and establishes an encrypted connection if the certificate is trusted and valid.
However, ordinary HTTPS does not necessarily prove the identity of the client to the server. The server can accept connections from any client that can establish a valid TLS connection, unless an additional authentication mechanism is implemented.
This can become a concern in service-to-service communication. Imagine an order management service communicating with a payment service. Both services run inside a private network, but the payment service should accept requests only from approved applications. Relying entirely on network isolation or a shared API key may not provide the level of identity verification required.
Mutual TLS, commonly called mTLS, addresses this requirement by authenticating both sides of the connection. The client verifies the server's certificate, and the server verifies the client's certificate. Each side uses a trusted Certificate Authority (CA) to validate the certificate presented by the other.
Node.js supports mTLS through its built-in TLS and HTTPS modules. The implementation itself is relatively straightforward, but certificate authority configuration requires careful attention. A common mistake is configuring the wrong CA certificate or trusting a broad collection of authorities when the application should accept certificates issued by only a specific internal CA.
The important part is not simply enabling client certificate authentication. It is establishing exactly which certificates the application should trust and what an authenticated client is allowed to do.
Understand How Mutual TLS Works
In a normal HTTPS connection, the server presents its certificate during the TLS handshake. The client checks whether the certificate chains to a trusted CA and whether the certificate is valid for the requested hostname.
With mTLS, the server also requests a certificate from the client. The client presents its certificate, and the server validates it against its configured trust authorities.
Consider two services:
Both services have their own certificates and private keys. The Order Service presents its client certificate, while the Payment Service presents its server certificate.
<text color="secondary" size="xs">Simplified mTLS authentication flow</text>
Order Service Payment Service
| |
| -------- ClientHello ---------------->|
| |
| <------- Server Certificate ----------|
| <------- Certificate Request ---------|
| |
| Verify server certificate |
| |
| -------- Client Certificate --------->|
| -------- Certificate Verify ---------->|
| |
| Verify client certificate
| |
| <--------- TLS Handshake Complete ---->|
| |
| <======= Encrypted HTTP Traffic =====>|
The client does not simply trust any certificate presented by the server, and the server does not simply accept any client certificate. Both sides validate the certificate chain against their configured trust authorities.
This distinction is important because mTLS is based on certificate trust, not merely on whether a certificate exists.
Understand the Role of Each Certificate
Before configuring Node.js, it helps to understand the certificates involved in an mTLS connection.
A typical deployment contains the following components:
Component | Purpose |
|---|
Server certificate | Identifies the HTTPS server |
Server private key | Proves possession of the server certificate's private key |
Client certificate | Identifies the connecting client |
Client private key | Proves possession of the client's private key |
Server CA | Issues or validates the server certificate |
Client CA | Issues or validates certificates presented by clients |
A Certificate Authority signs certificates and establishes a chain of trust. A certificate can be issued directly by a root CA or by an intermediate CA that chains back to a trusted root.
For example, an organization might use separate certificate hierarchies:
Company Root CA
|
+----------------------+
| |
Server Intermediate CA Client Intermediate CA
| |
Payment Server Cert Order Service Cert
The Payment Service should trust the CA hierarchy authorized to issue client certificates. The Order Service should trust the CA hierarchy authorized to issue the payment server's certificate.
Using separate issuing authorities makes it easier to control which identities are allowed to authenticate to which services.
A certificate issued by a trusted CA is not automatically authorized to perform every operation. Certificate validation establishes trust in the certificate issuer and the certificate's validity. Application authorization must still determine what the identified service is allowed to access.
Configure the Node.js HTTPS Server to Require Client Certificates
The server is responsible for requesting and validating client certificates.
Node.js provides the https.createServer() method, which accepts TLS configuration options. Three options are particularly important for mTLS:
cert and key identify the server.
ca specifies the CA certificates trusted when validating incoming client certificates.
requestCert and rejectUnauthorized control client certificate authentication.
Consider the following implementation:
import https from 'node:https';
import { readFileSync } from 'node:fs';
const serverOptions = {
key: readFileSync('./certs/server-key.pem'),
cert: readFileSync('./certs/server-cert.pem'),
ca: [
readFileSync('./certs/client-ca.pem')
],
requestCert: true,
rejectUnauthorized: true
};
const server = https.createServer(
serverOptions,
(req, res) => {
res.writeHead(200, {
'content-type': 'application/json'
});
res.end(JSON.stringify({
message: 'Mutual TLS authentication successful'
}));
}
);
server.listen(8443, () => {
console.log('mTLS server listening on port 8443');
});
The server uses its own certificate and private key to identify itself to connecting clients. The ca option contains the CA certificates used to validate client certificates.
The requestCert: true setting tells the server to request a certificate during the TLS handshake. However, requesting a certificate does not by itself guarantee that the connection will be rejected when the client presents an invalid certificate.
That responsibility belongs to rejectUnauthorized: true.
When this option is enabled, Node.js rejects clients whose certificates cannot be validated against the configured CA authorities. The HTTP request handler is not reached for an unauthorized TLS connection.
This is the preferred configuration for a production service that requires strict client certificate authentication.
The Most Important Detail: Configure the Correct CA
The ca option is one of the easiest parts of mTLS to misunderstand because it is used by both HTTPS clients and HTTPS servers.
Its meaning depends on which side of the connection is being configured.
On the server, ca identifies the authorities trusted to issue client certificates. On the client, ca identifies the authorities trusted to issue the server certificate.
For example, consider the following configuration:
const serverOptions = {
key: readFileSync('./certs/server-key.pem'),
cert: readFileSync('./certs/server-cert.pem'),
ca: [
readFileSync('./certs/server-ca.pem')
],
requestCert: true,
rejectUnauthorized: true
};
The application is using server-ca.pem to validate incoming client certificates. If that CA only issued the server certificate and did not issue the client certificate, the client's certificate validation will fail.
The correct configuration should use the CA hierarchy that issued the client certificate:
const serverOptions = {
key: readFileSync('./certs/server-key.pem'),
cert: readFileSync('./certs/server-cert.pem'),
ca: [
readFileSync('./certs/client-ca.pem')
],
requestCert: true,
rejectUnauthorized: true
};
The naming of certificate files can make this mistake difficult to identify. A file called server-ca.pem might actually be the CA that issues client certificates, depending on how the organization has designed its certificate infrastructure.
Do not rely on filenames alone. Verify the certificate subject, issuer, certificate chain, and intended usage before configuring trust.
There is another important behavior to understand: when a custom ca option is supplied, Node.js uses the supplied CA certificates for that TLS context rather than automatically adding the normal public root CA collection.
This matters when an application needs to trust both an internal CA and public certificate authorities. If the application connects to public services as well as internal services, replacing the default trust set with only an internal CA can cause otherwise valid HTTPS connections to fail.
For an internal mTLS connection, using a dedicated CA trust set is often desirable. For a client that must trust both internal and public services, explicitly construct the appropriate trust configuration rather than assuming that the default public roots will remain available.
Configure the Node.js Client to Present Its Certificate
The client must also provide its certificate and private key. At the same time, it must validate the server certificate.
The following example uses the built-in HTTPS module:
import https from 'node:https';
import { readFileSync } from 'node:fs';
const clientOptions = {
hostname: 'payment.internal.example',
port: 8443,
path: '/payments',
method: 'GET',
key: readFileSync('./certs/client-key.pem'),
cert: readFileSync('./certs/client-cert.pem'),
ca: [
readFileSync('./certs/server-ca.pem')
],
rejectUnauthorized: true
};
const request = https.request(
clientOptions,
(response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
console.log('Status:', response.statusCode);
console.log('Response:', data);
});
}
);
request.on('error', (error) => {
console.error('HTTPS request failed:', error.message);
});
request.end();
The client presents its certificate and private key to the server during the TLS handshake. Its ca configuration tells Node.js which CA certificates to trust when validating the server.
The rejectUnauthorized: true setting ensures that the client does not silently accept an untrusted server certificate.
The server hostname must also match the certificate's Subject Alternative Name (SAN). A certificate issued for payment.internal.example should not be assumed valid for localhost or another hostname.
Do not solve hostname verification failures by setting rejectUnauthorized: false or by replacing hostname verification with a callback that always succeeds. That removes an important part of TLS authentication and can expose the client to impersonation attacks.
For production applications, use the actual service hostname covered by the certificate and maintain proper certificate issuance and renewal processes.
Verify Certificate Identity Separately From Trust
A successfully validated certificate proves that the certificate chains to an authority trusted by the server. It does not necessarily mean that the client should have access to every API endpoint.
For example, suppose the same internal CA issues certificates to three services:
Order Service
Reporting Service
Notification Service
All three certificates may be trusted by the Payment Service. However, the Reporting Service should not automatically receive permission to initiate payments.
The application must identify the authenticated peer and apply an authorization policy.
Node.js exposes information about the peer certificate through the TLS socket. For an HTTPS request, the certificate can be inspected using req.socket.getPeerCertificate().
For example:
function getClientIdentity(req) {
if (!req.socket.authorized) {
throw new Error('Client certificate is not authorized');
}
const certificate = req.socket.getPeerCertificate();
if (!certificate || Object.keys(certificate).length === 0) {
throw new Error('Client certificate is missing');
}
return {
subject: certificate.subject,
issuer: certificate.issuer,
fingerprint256: certificate.fingerprint256
};
}
The application can then map the verified certificate identity to a service account or an authorization policy.
For example, it might allow only an approved certificate identity to access the payment creation endpoint.
Do not use a common certificate subject such as CN=internal-service as the only authorization rule if several services can receive certificates with the same subject. Prefer a well-defined identity scheme, such as controlled certificate subjects, SAN entries, or managed certificate fingerprints.
Also remember that certificate fingerprints change when certificates are renewed. If fingerprints are used for authorization, certificate rotation must update the corresponding identity mappings.
Avoid Accepting Untrusted Certificates During Production Rollouts
Sometimes an organization introduces mTLS gradually. Not every internal service may have a client certificate when the server is first configured.
Node.js allows a server to request a certificate without immediately rejecting every unauthorized client by setting rejectUnauthorized: false.
For example:
const serverOptions = {
key: readFileSync('./certs/server-key.pem'),
cert: readFileSync('./certs/server-cert.pem'),
ca: [
readFileSync('./certs/client-ca.pem')
],
requestCert: true,
rejectUnauthorized: false
};
In this configuration, Node.js records the certificate validation result, but the application must inspect it before processing the request.
const server = https.createServer(
serverOptions,
(req, res) => {
if (!req.socket.authorized) {
res.writeHead(401, {
'content-type': 'application/json'
});
return res.end(JSON.stringify({
message: 'Valid client certificate required'
}));
}
res.writeHead(200, {
'content-type': 'application/json'
});
res.end(JSON.stringify({
message: 'Authenticated client'
}));
}
);
This can be useful during a controlled migration because teams can identify which clients are presenting certificates and which are failing validation.
However, it introduces an additional responsibility: every request-handling path must enforce the authorization check. If one route or middleware path forgets to check req.socket.authorized, an untrusted client may reach application logic.
For this reason, optional certificate validation should be a temporary migration technique, not the normal production configuration for a service that requires mTLS.
Once the client population has been migrated, enable strict validation with rejectUnauthorized: true.
Troubleshoot Common mTLS Certificate Problems
When an mTLS connection fails, the error often occurs before the application receives an HTTP request. This can make troubleshooting confusing because developers may see a connection failure without receiving an HTTP status code.
The following problems are particularly common.
Problem | Likely cause | What to check |
|---|
UNABLE_TO_VERIFY_LEAF_SIGNATURE | Missing or incomplete certificate chain | Intermediate certificates and trusted CA |
SELF_SIGNED_CERT_IN_CHAIN | Certificate chain contains an untrusted self-signed certificate | Correct CA configuration |
ERR_TLS_CERT_ALTNAME_INVALID | Server hostname does not match the certificate SAN | Requested hostname and certificate SAN |
CERT_HAS_EXPIRED | Certificate validity period has ended | Certificate expiration and renewal |
Client certificate rejected | Wrong CA or incomplete client chain | Client certificate issuer and server trust configuration |
No client certificate presented | Client did not provide certificate and key | HTTPS client configuration |
One particularly useful diagnostic event is tlsClientError, which is emitted by the HTTPS server when a TLS error occurs before the secure connection is established.
server.on('tlsClientError', (error, socket) => {
console.error('TLS client connection failed:', {
code: error.code,
remoteAddress: socket.remoteAddress
});
});
This helps identify failed handshakes that never reach the normal HTTP request handler.
Avoid logging private keys, complete certificate configuration, or sensitive connection details while investigating these failures. Certificate metadata such as the issuer, subject, expiration date, and fingerprint is generally more useful for diagnosis.
Manage Certificate Rotation and Trust Changes
mTLS security depends on certificates remaining valid and trusted. Certificate management should therefore be part of the application's operational design.
Certificates have expiration dates, and organizations need a process for issuing replacements before they expire. If a client certificate expires without renewal, the server will reject new connections from that client. Similarly, if a server certificate expires, clients may refuse to connect.
CA rotation requires additional care. Suppose a company replaces its internal client CA. If the Payment Service immediately stops trusting the old CA, services that have not yet received certificates from the new CA will lose connectivity.
A safer approach is to introduce the new CA into the server's trust configuration while the old CA is still trusted. Then migrate clients to certificates issued by the new authority, verify that all clients have moved successfully, and finally remove the old CA.
This overlapping trust period reduces the risk of an unexpected service outage.
Also consider the lifecycle of long-lived HTTP connections. Updating a certificate file does not automatically replace certificates on already established TLS connections. Depending on the deployment architecture, the service may need a controlled restart or TLS context update so that new connections use the replacement certificate.
Certificate revocation also deserves attention. Trusting a CA and checking certificate expiration are not the same as having a complete revocation strategy. Define how compromised client certificates will be disabled, how the server will receive updated revocation information, and how quickly the organization expects that change to take effect.
Best Practices for Production mTLS
A reliable mTLS implementation starts with a clearly defined certificate trust model. Use dedicated CA hierarchies where practical, separate server and client certificate issuance, and verify certificate chains rather than relying on filenames or assumptions.
Keep strict certificate validation enabled in production. Use requestCert: true and rejectUnauthorized: true when every connecting client must present a trusted certificate. Avoid disabling hostname verification on the client.
Do not confuse authentication with authorization. A valid certificate establishes the identity of a trusted peer, but application code must still decide which services can access which operations.
Store private keys securely, restrict access to certificate files, and define a renewal process before certificates expire. Plan CA rotation so that old and new authorities can overlap during migration without creating unnecessary outages.
Finally, monitor TLS handshake failures and certificate expiration. A certificate that is technically valid today can still become an operational problem if nobody knows when it will expire or which services depend on it.
Summary
Mutual TLS provides certificate-based authentication for both sides of a connection. It is particularly useful when Node.js applications communicate with internal services that should not accept requests from arbitrary clients.
The most important configuration detail is understanding the role of the ca option. On an HTTPS server, it identifies the authorities trusted to issue client certificates. On an HTTPS client, it identifies the authorities trusted to issue the server certificate.
Use requestCert: true and rejectUnauthorized: true to enforce client certificate validation during the TLS handshake. Then apply application-level authorization to determine what the authenticated service is allowed to do.
A secure mTLS implementation also requires careful certificate management, hostname verification, private-key protection, renewal planning, and controlled CA rotation. When these responsibilities are handled properly, mTLS provides a strong foundation for authenticating communication between Node.js services without relying entirely on shared API keys or network isolation.
Join the conversation! Your thoughts help the community grow.