LDAPts Client

8.1.7 · active · verified Tue Apr 21

LDAPts is a modern, TypeScript-first LDAP client library for Node.js, providing a robust API to interact with LDAP directory servers, including Active Directory. It supports both `ldap://` and `ldaps://` protocols, offering comprehensive options for secure connections using TLS. The library is currently at version 8.1.7 and maintains an active release cadence, frequently publishing bug fixes and minor enhancements. Key features include client creation with configurable timeouts, strict DN parsing, and support for various LDAP operations such as bind, add, compare, delete, modify, and search. It differentiates itself by offering full TypeScript type definitions out-of-the-box, targeting recent Node.js versions (>=20), and internally handling BER encoding/decoding, reducing external dependencies.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create an LDAPts client, bind to an LDAP server using credentials from environment variables, perform a basic search operation for entries, and then unbind gracefully. It includes basic error handling for common LDAP issues.

import { Client } from 'ldapts';

async function connectAndSearch() {
  const ldapUrl = process.env.LDAP_URL ?? 'ldap://localhost:389';
  const bindDN = process.env.LDAP_BIND_DN ?? 'cn=admin,dc=example,dc=com';
  const bindPassword = process.env.LDAP_BIND_PASSWORD ?? 'password';
  const searchBase = process.env.LDAP_SEARCH_BASE ?? 'dc=example,dc=com';
  const searchFilter = process.env.LDAP_SEARCH_FILTER ?? '(objectClass=*)';

  const client = new Client({
    url: ldapUrl,
    timeout: 5000, // Milliseconds client should let operations live for
    connectTimeout: 5000, // Milliseconds client should wait for TCP connection
    tlsOptions: {
      minVersion: 'TLSv1.2', // Enforce minimum TLS version
      rejectUnauthorized: false // Set to true in production with valid certs
    },
    strictDN: true
  });

  try {
    console.log(`Attempting to bind as ${bindDN} to ${ldapUrl}...`);
    await client.bind(bindDN, bindPassword);
    console.log('LDAP bind successful!');

    console.log(`Performing search under '${searchBase}' with filter '${searchFilter}'...`);
    const { searchEntries, searchReferences } = await client.search(
      searchBase,
      {
        filter: searchFilter,
        scope: 'sub',
        attributes: ['dn', 'cn', 'mail'], // Request specific attributes
        sizeLimit: 10 // Limit results for example
      }
    );

    if (searchEntries.length > 0) {
      console.log(`Found ${searchEntries.length} entries.`);
      searchEntries.forEach(entry => {
        console.log(`- DN: ${entry.dn}, CN: ${entry.cn ?? 'N/A'}, Mail: ${entry.mail ?? 'N/A'}`);
      });
    } else {
      console.log('No entries found.');
    }

    console.log('Unbinding from LDAP server...');
    await client.unbind();
    console.log('Unbind successful.');

  } catch (error: any) {
    console.error('LDAP operation failed:', error.message);
    // Specific error handling for common LDAP issues
    if (error.code === 'ETIMEDOUT') {
      console.error('Timeout occurred. Check network connectivity or server responsiveness.');
    } else if (error.code === 'LDAP_INVALID_CREDENTIALS') {
      console.error('Invalid credentials provided for bind operation.');
    } else if (error.message.includes('ECONNREFUSED')) {
      console.error('Connection refused. Ensure the LDAP server is running and accessible.');
    }
    process.exit(1);
  } finally {
    if (client.connected) {
      await client.unbind().catch(e => console.error('Error during final unbind:', e.message));
    }
  }
}

connectAndSearch();

view raw JSON →