Create ssl / https server in nodejs

Sometimes there are needs to create https in your node application itself to create real life scenario or may be to test things like http/2 server push. Today I will show you how to create https server in node js, both with and without express.
I will also talk about ssl and what is the significance of it.

A small talk on https

With http or Hyper Text Transfer Protocol two computers (the client and the server) communicates without any encryption. However https means Hyper Text Transfer Protocol Secure and with this protocol the client and the server passes messages with encryption. This is to prevent any hacker to steal the user’s data in between.

A bit on ssl

If you know about https, I’m sure you’ve heard the term SSL too. SSL or Secure Sockets Layer is a standard security technology for establishing an encrypted link between a server and a client. So basically ssl has the key to encrypt or decrypt the informations.
Apart from a key, ssl also has a certificate. This certificate is used to verify your identity. A certificate can be self signed or signed by a CA (Certificate Authority).
Both self or CA signed certificates plays no role on encryption. If you have a self signed certificate, then also the https encryption will work great. But CA signed certificates are trusted. Those authorities are known to browser vendors and also other internet players. Thus, browsers and users will trust your site more if it’s signed by CA.

Create key and certificate

To get a signed by certification authority, you can use websites like godaddy, hostgator etc. And to generate a self signed certificate you can use the following way.

OpenSSL is a command line tool that can be used for generating ssl keys and certificates. In Mac and Linux it will be pre installed, but in windows probably you have to manually install it.

Anyway, assuming you have openssl installed in your machine, below is a command to generate key and certificate. After running the command, it will ask you couple of questions; just answer them.

Now that we have the private key and certificate with you; it’s time to use them in our node application. Remember you can generate the private key and certificate in any location of your computer. I am putting these two in the root folder.

Create an https node server

All you need to do is to use the module https instead of http to create the server; and pass the private key and certificate as options. And that’s it. Now you can access https://localhost:8000/. Remember as you are using self signed certificate and not from any CA, the browser will try to reject the connection. But you can anyway proceed to the webpage.

Do it with expressJS

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.