How to get the server's TLS certificate information? #1916
-
https.get(url, { headers, timeout, agent: false }, res => {
const cert = res.connection.getPeerCertificate()
const protocol = res.connection.getProtocol()
const valid = res.socket.authorized
const error = res.socket.authorizationError
console.log(cert, protocol, valid, error)
})Is there a way to get the same data from Got? |
Beta Was this translation helpful? Give feedback.
Answered by
sindresorhus
Oct 11, 2025
Replies: 2 comments
-
|
Just noticed this discussion thread after opening an issue here #2096 |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
You can access the TLS certificate through import got from 'got';
const response = await got('https://example.com');
// Access certificate info
if (response.socket && response.socket.getPeerCertificate) {
const cert = response.socket.getPeerCertificate();
const protocol = response.socket.getProtocol();
const valid = response.socket.authorized;
const error = response.socket.authorizationError;
console.log(cert, protocol, valid, error);
}Important caveats:
const response = await got('https://example.com', {
agent: {
https: false
}
});
More reliable approach using import got from 'got';
let certificate;
const response = await got('https://example.com', {
https: {
checkServerIdentity: (hostname, cert) => {
certificate = cert;
return undefined; // Accept the certificate
}
}
});
console.log(certificate);This captures the certificate during the TLS handshake, before the connection is established, making it more relible than accessing it after the response. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sindresorhus
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can access the TLS certificate through
response.socket, but there are some caveats:Important caveats:
getPeerCertificate()may return an empty object on subsequent requests to the same host. To avoid this, disable the agent: