Crypto
x509.checkHost()
Checks a hostname against an X.509 certificate identity. A successful name match does not establish chain trust or validity dates. The example uses a disposable certificate with a DNS SAN. Tested on Node.js 22.16.0. Example output (one line per entry): ["localhost true"].
Formal Syntax & Structure
nodejs syntaxnodejs
x509.checkHost(name[, options])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | Expected hostname. |
| options | object | Name matching options. |
Return Value
string | undefined
Matching name if present.
Working Example
Example Snippetnodejs
import tls from 'node:tls';import { execFileSync } from 'node:child_process';import { mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';const dir = mkdtempSync(join(tmpdir(), 'bm-tls-'));let server, client;try { execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', join(dir, 'key.pem'), '-out', join(dir, 'cert.pem'), '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost'], { stdio: 'ignore', timeout: 3000 }); const cert = readFileSync(join(dir, 'cert.pem')), key = readFileSync(join(dir, 'key.pem')); const { X509Certificate } = await import('node:crypto'); const x = new X509Certificate(cert); console.log(x.checkHost('localhost'), x.checkHost('other.invalid') === undefined);}finally { client?.destroy(); if (server?.listening) await new Promise(resolve => server.close(resolve)); rmSync(dir, { recursive: true, force: true });}