Skip to content

Instantly share code, notes, and snippets.

Forked from anhldbk/
Created September 19, 2019 11:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
TLS client & server in NodeJS

1. Overview

This is an example of using module tls in NodeJS to create a client securely connecting to a TLS server.

It is a modified version from documentation about TLS, in which:

  • The server is a simple echo one. Clients connect to it, get the same thing back if they send anything to the server.
  • The server is a TLS-based server.
  • Clients somehow get the server's public key and use it to work securely with the server

2. Preparation

We need to generate keys & certs for the server. Pay attention to Common Name (e.g. server FQDN or YOUR name) when creating server-csr.pem. It should be your domain name.

$ mkdir tls
$ cd tls
$ openssl genrsa -out server-key.pem 4096
$ openssl req -new -key server-key.pem -out server-csr.pem
$ openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem

For example:

$ openssl req -new -key server-key.pem -out server-csr.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
Country Name (2 letter code) [AU]:VN
State or Province Name (full name) [Some-State]:Hanoi
Locality Name (eg, city) []:Hanoi
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Evolas Technologies
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []
Email Address []

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

3. Run the demo

$ node server.js &
$ node client.js &

You may have following things printed out:

server bound
server connected unauthorized
client connected authorized
const tls = require('tls');
const fs = require('fs');
const options = {
ca: [ fs.readFileSync('server-cert.pem') ]
var socket = tls.connect(8000, '', options, () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.on('data', (data) => {
socket.on('end', () => {
const tls = require('tls');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
rejectUnauthorized: true,
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
server.listen(8000, () => {
console.log('server bound');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment