Skip to content

Enabling HTTPS for Your Express App

Last updated on November 21, 2022

I am gonna show you the usage of SSL certificates along with Express JS-based applications. Once you have your private key and certificate, using them in your app is easy.

Enabling HTTPS for Your Express App

HTTP Server

Let’s revisit how we’ve been creating our HTTP server:

const express = require('express');
const http = require('http');
const app = express();

http.createServer(options, app).listen(3000, function(){
console.log('Express started in 3000');
});

HTTPS Server

Switching over to HTTPS is simple. Put your private key and SSL cert in a subdirectory called SSL. Then you just use the https module instead of HTTP, and pass an options object along to the createServer method:

const express = require('express');
const https = require('https');
const fs = require('fs');
const app = express();

var options = {
key: fs.readFileSync(__dirname + '/ssl/pem-arjunphp.pem');
cert: fs.readFileSync(__dirname + '/ssl/crt-arjunphp.crt');
};
https.createServer(options, app).listen(3000, function(){
console.log('Express started in 3000');
});

That’s it. Assuming you’re still running your server on port 3000, you can now connect to https://localhost:3000. If you try to connect to http://localhost:3000, it will simply time out.

As we’ve seen, it’s very easy to use HTTPS with Express, and for development, it will work fine. However, when you want to scale your site out to handle more traffic, you will want to use a proxy server such as Nginx. I will cover it in the next tutorial.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments