Fix Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE in Node.js
This error means Node.js cannot verify the SSL/TLS certificate presented by the server because the certificate chain is incomplete or the CA is not trusted. Fix it by providing the full certificate chain, setting the correct CA bundle, or ensuring your Node.js version has up-to-date root certificates.
Reading the Stack Trace
Here's what each line means:
- at TLSSocket.onConnectSecure (node:_tls_wrap:1674:34): The TLS handshake completed but certificate verification failed because the chain could not be validated.
- at ssl.onhandshakedone (node:_tls_wrap:871:12): The SSL handshake finished at the protocol level but trust verification rejected the certificate.
- at Request._callback (src/services/apiClient.js:45:14): Your API client at line 45 made an HTTPS request to a server with an incomplete certificate chain.
Common Causes
1. Server sends incomplete certificate chain
The remote server does not include intermediate certificates in its TLS response, leaving a gap in the chain to the root CA.
const https = require('https');
https.get('https://api.example.com/data', (res) => {
// Fails because server doesn't send intermediate cert
});
2. Self-signed certificate without custom CA
The server uses a self-signed or internal CA certificate that Node.js does not trust by default.
const axios = require('axios');
axios.get('https://internal-api.corp.com/data');
// Internal CA is not in Node's trusted CA store
3. Disabling TLS verification as a workaround
Setting NODE_TLS_REJECT_UNAUTHORIZED=0 or rejectUnauthorized: false bypasses all certificate checks, creating a security vulnerability.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // INSECURE
The Fix
Provide the internal CA certificate to the HTTPS agent so Node.js can verify the server's certificate chain. Keep rejectUnauthorized: true to maintain security while trusting the internal CA.
const axios = require('axios');
async function fetchData() {
const response = await axios.get('https://internal-api.corp.com/data');
return response.data;
}
const axios = require('axios');
const https = require('https');
const fs = require('fs');
const path = require('path');
const caCert = fs.readFileSync(path.resolve(__dirname, '../certs/internal-ca.pem'));
const httpsAgent = new https.Agent({
ca: caCert,
rejectUnauthorized: true,
});
async function fetchData() {
const response = await axios.get('https://internal-api.corp.com/data', {
httpsAgent,
});
return response.data;
}
Testing the Fix
const axios = require('axios');
const { fetchData } = require('./apiClient');
jest.mock('axios');
describe('fetchData', () => {
it('returns data from the API', async () => {
axios.get.mockResolvedValue({ data: { result: 'ok' } });
const data = await fetchData();
expect(data.result).toBe('ok');
});
it('passes httpsAgent with custom CA', async () => {
axios.get.mockResolvedValue({ data: {} });
await fetchData();
const callArgs = axios.get.mock.calls[0];
expect(callArgs[1]).toHaveProperty('httpsAgent');
});
it('throws on connection failure', async () => {
axios.get.mockRejectedValue(new Error('UNABLE_TO_VERIFY_LEAF_SIGNATURE'));
await expect(fetchData()).rejects.toThrow('UNABLE_TO_VERIFY_LEAF_SIGNATURE');
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/nodejs-tls-certificate-error,git add src/services/apiClient.js src/services/__tests__/apiClient.test.js,git commit -m "fix: provide custom CA certificate for internal API TLS verification",git push origin fix/nodejs-tls-certificate-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Obtain the correct CA certificate or intermediate certificate chain.
- Store the CA cert file securely and include it in the deployment.
- Update the HTTPS agent to use the CA cert with rejectUnauthorized: true.
- Run tests and verify the connection works.
- Open a PR, merge after CI passes, and verify in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Absolutely not in production. This disables all certificate verification, making your application vulnerable to man-in-the-middle attacks. Always provide the correct CA certificate instead.
Use 'openssl s_client -connect host:443 -showcerts' to see what certificates the server sends. Identify any missing intermediates and add them to your CA bundle.