How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Node.js · JavaScript

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

Error: unable to verify the first certificate at TLSSocket.onConnectSecure (node:_tls_wrap:1674:34) at TLSSocket.emit (node:events:513:28) at TLSSocket._finishInit (node:_tls_wrap:1085:8) at ssl.onhandshakedone (node:_tls_wrap:871:12) at Request._callback (src/services/apiClient.js:45:14) at self.callback (node_modules/request/request.js:185:22) at Request.emit (node:events:513:28) at ClientRequest.emit (node:events:513:28) at TLSSocket.socketErrorListener (node:_http_client:502:9) at TLSSocket.emit (node:events:513:28)

Here's what each line means:

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.

Before (broken)
const axios = require('axios');

async function fetchData() {
  const response = await axios.get('https://internal-api.corp.com/data');
  return response.data;
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Obtain the correct CA certificate or intermediate certificate chain.
  2. Store the CA cert file securely and include it in the deployment.
  3. Update the HTTPS agent to use the CA cert with rejectUnauthorized: true.
  4. Run tests and verify the connection works.
  5. 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.