Choose LDAPS when the directory exposes a dedicated TLS endpoint, or StartTLS when it expects an existing LDAP connection to be upgraded. Both examples validate the server certificate.
Security
Do not set rejectUnauthorized: false. Fix the trust chain or server certificate instead.
Link to Shared environmentShared environment
export LDAP_BIND_DN='uid=service,ou=system,dc=example,dc=com'
export LDAP_PASSWORD='replace-me'
export LDAP_CA_FILE='/path/to/directory-ca.pem'
Link to LDAPSLDAPS
Set LDAP_URL to an ldaps:// endpoint:
const fs = require('node:fs')
const ldap = require('ldapjs')
for (const name of ['LDAP_URL', 'LDAP_BIND_DN', 'LDAP_PASSWORD', 'LDAP_CA_FILE']) {
if (!process.env[name]) throw new Error(`Missing ${name}`)
}
if (!process.env.LDAP_URL.startsWith('ldaps://')) {
throw new Error('LDAP_URL must use ldaps:// for this example')
}
const client = ldap.createClient({
url: process.env.LDAP_URL,
tlsOptions: { ca: [fs.readFileSync(process.env.LDAP_CA_FILE)] }
})
client.on('error', (err) => console.error('LDAPS error:', err.message))
client.bind(process.env.LDAP_BIND_DN, process.env.LDAP_PASSWORD, (err) => {
if (err) {
client.destroy()
throw err
}
console.log('LDAPS bind succeeded')
client.unbind()
})
Link to StartTLSStartTLS
Set LDAP_URL to an ldap:// endpoint:
const fs = require('node:fs')
const ldap = require('ldapjs')
for (const name of ['LDAP_URL', 'LDAP_BIND_DN', 'LDAP_PASSWORD', 'LDAP_CA_FILE']) {
if (!process.env[name]) throw new Error(`Missing ${name}`)
}
if (!process.env.LDAP_URL.startsWith('ldap://')) {
throw new Error('LDAP_URL must use ldap:// for this example')
}
const client = ldap.createClient({ url: process.env.LDAP_URL })
client.on('error', (err) => console.error('LDAP error:', err.message))
client.starttls({
ca: [fs.readFileSync(process.env.LDAP_CA_FILE)]
}, (tlsError) => {
if (tlsError) {
client.destroy()
throw tlsError
}
client.bind(process.env.LDAP_BIND_DN, process.env.LDAP_PASSWORD, (bindError) => {
if (bindError) {
client.destroy()
throw bindError
}
console.log('StartTLS bind succeeded')
client.unbind()
})
})
If the StartTLS upgrade fails, the example destroys the connection and never attempts a plaintext bind.