Enabling HTTPS on express.js

542,142

Solution 1

In express.js (since version 3) you should use that syntax:

var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

// your express configuration here

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

In that way you provide express middleware to the native http/https server

If you want your app running on ports below 1024, you will need to use sudo command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).

Solution 2

First, you need to create selfsigned.key and selfsigned.crt files. Go to Create a Self-Signed SSL Certificate Or do following steps.

Go to the terminal and run the following command.

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt

  • After that put the following information
  • Country Name (2 letter code) [AU]: US
  • State or Province Name (full name) [Some-State]: NY
  • Locality Name (eg, city) []:NY
  • Organization Name (eg, company) [Internet Widgits Pty Ltd]: xyz (Your - Organization)
  • Organizational Unit Name (eg, section) []: xyz (Your Unit Name)
  • Common Name (e.g. server FQDN or YOUR name) []: www.xyz.com (Your URL)
  • Email Address []: Your email

After creation adds key & cert file in your code, and pass the options to the server.

const express = require('express');
const https = require('https');
const fs = require('fs');
const port = 3000;

var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
var options = {
  key: key,
  cert: cert
};

app = express()
app.get('/', (req, res) => {
   res.send('Now using https..');
});

var server = https.createServer(options, app);

server.listen(port, () => {
  console.log("server starting on port : " + port)
});
  • Finally run your application using https.

More information https://github.com/sagardere/set-up-SSL-in-nodejs

Solution 3

I ran into a similar issue with getting SSL to work on a port other than port 443. In my case I had a bundle certificate as well as a certificate and a key. The bundle certificate is a file that holds multiple certificates, node requires that you break those certificates into separate elements of an array.

    var express = require('express');
    var https = require('https');
    var fs = require('fs');

    var options = {
      ca: [fs.readFileSync(PATH_TO_BUNDLE_CERT_1), fs.readFileSync(PATH_TO_BUNDLE_CERT_2)],
      cert: fs.readFileSync(PATH_TO_CERT),
      key: fs.readFileSync(PATH_TO_KEY)
    };

    app = express()

    app.get('/', function(req,res) {
        res.send('hello');
    });

    var server = https.createServer(options, app);

    server.listen(8001, function(){
        console.log("server running at https://IP_ADDRESS:8001/")
    });

In app.js you need to specify https and create the server accordingly. Also, make sure that the port you're trying to use is actually allowing inbound traffic.

Solution 4

Including Points:

  1. SSL setup
    1. In config/local.js
    2. In config/env/production.js

HTTP and WS handling

  1. The app must run on HTTP in development so we can easily debug our app.
  2. The app must run on HTTPS in production for security concern.
  3. App production HTTP request should always redirect to https.

SSL configuration

In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env folder and each file contains settings for particular env.

Sails first looks in config/env folder and then look forward to config/ *.js

Now lets setup ssl in config/local.js.

var local = {
   port: process.env.PORT || 1337,
   environment: process.env.NODE_ENV || 'development'
};

if (process.env.NODE_ENV == 'production') {
    local.ssl = {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
    };
    local.port = 443; // This port should be different than your default port
}

module.exports = local;

Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)

Or in production.js

module.exports = {
    port: 443,
    ssl: {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: [
            require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
        ],
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
    }
};

http/https & ws/wss redirection

Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.

There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.

So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.

In config/bootstrap.js (Create http server and redirect all request to https)

module.exports.bootstrap = function(cb) {
    var express = require("express"),
        app = express();

    app.get('*', function(req, res) {  
        if (req.isSocket) 
            return res.redirect('wss://' + req.headers.host + req.url)  

        return res.redirect('https://' + req.headers.host + req.url)  
    }).listen(80);
    cb();
};

Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com

Solution 5

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);
Share:
542,142
Alan
Author by

Alan

“Often when you think you're at the end of something, you're at the beginning of something else.” ― Fred Rogers

Updated on July 27, 2022

Comments

  • Alan
    Alan almost 2 years

    I'm trying to get HTTPS working on express.js for node, and I can't figure it out.

    This is my app.js code.

    var express = require('express');
    var fs = require('fs');
    
    var privateKey = fs.readFileSync('sslcert/server.key');
    var certificate = fs.readFileSync('sslcert/server.crt');
    
    var credentials = {key: privateKey, cert: certificate};
    
    
    var app = express.createServer(credentials);
    
    app.get('/', function(req,res) {
        res.send('hello');
    });
    
    app.listen(8000);
    

    When I run it, it seems to only respond to HTTP requests.

    I wrote simple vanilla node.js based HTTPS app:

    var   fs = require("fs"),
          http = require("https");
    
    var privateKey = fs.readFileSync('sslcert/server.key').toString();
    var certificate = fs.readFileSync('sslcert/server.crt').toString();
    
    var credentials = {key: privateKey, cert: certificate};
    
    var server = http.createServer(credentials,function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    });
    
    server.listen(8000);
    

    And when I run this app, it does respond to HTTPS requests. Note that I don't think the toString() on the fs result matters, as I've used combinations of both and still no es bueno.


    EDIT TO ADD:

    For production systems, you're probably better off using Nginx or HAProxy to proxy requests to your nodejs app. You can set up nginx to handle the ssl requests and just speak http to your node app.js.

    EDIT TO ADD (4/6/2015)

    For systems on using AWS, you are better off using EC2 Elastic Load Balancers to handle SSL Termination, and allow regular HTTP traffic to your EC2 web servers. For further security, setup your security group such that only the ELB is allowed to send HTTP traffic to the EC2 instances, which will prevent external unencrypted HTTP traffic from hitting your machines.


  • Setthase
    Setthase almost 12 years
    All is written here: github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.‌​x Paragraph Application function
  • Setthase
    Setthase almost 12 years
    Yes, you can have http and https using that same server configuration.
  • ebohlman
    ebohlman almost 12 years
    Note that although 443 is the default port for HTTPS, during development you probably want to use something like 8443 because most systems don't allow non-root listeners on low-numbered ports.
  • Marcelo Teixeira Ruggeri
    Marcelo Teixeira Ruggeri almost 10 years
    Man, it works like magic :) It accepts .pem files too, well as it should anyway
  • Muhammad Umer
    Muhammad Umer about 9 years
    express 4 it doesn't work, it works for localhost:80 but not https://localhost:443
  • Gianfranco P.
    Gianfranco P. over 8 years
    if you're going to use nginx for reverse proxy, that can handle the ssl certs for you instead of node
  • inf3rno
    inf3rno about 8 years
    @GianPaJ And what would be the advantage of that? Installing another program instead of writing a few lines?
  • Gianfranco P.
    Gianfranco P. about 8 years
    @inf3rno nginx is not only for SSL, it handles static content better and is easier for setting caching headers, etc
  • inf3rno
    inf3rno about 8 years
    @GianPaJ And it handles websockets much worse.
  • user557657
    user557657 over 6 years
    @codename- In my case, I have two express apps running as frontend and backend on different ports. I am able to enable https on the backend but not sure if follow the same approach. Frontend app runs on port 5000 and backend runs on 4433. Frontend provides login page to the user but all the logic reside in the backend app running on 4433. Please guide me. Thanks
  • Muhammad Umar
    Muhammad Umar over 6 years
    i have a key and a bundled cert, i am not sure what cert: fs.readFileSync(PATH_TO_CERT), would be and how to "break" the bundled cert, there are like 20+ keys in cert if u ask me :)
  • khmub
    khmub over 6 years
    Could any one give hints : curl -v localhost:8443/api/v1 * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8443 (#0) * found 148 certificates in /etc/ssl/certs/ca-certificates.crt * found 592 certificates in /etc/ssl/certs * ALPN, offering http/1.1 * SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256 * server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none * Closing connection 0 curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
  • GavinBelson
    GavinBelson over 5 years
    Don't forget to use https://localhost:8443 instead of http in your browser for development.
  • Hayden Thring
    Hayden Thring almost 5 years
    @MuhammadUmar you dont have to break the bundled or even specify it if you dont have one, you will have a bundle cert if applicable, and cert(public key) and key(private key)
  • Hayden Thring
    Hayden Thring almost 5 years
    @eomoto thanks bud ! this is the best, you totally nailed the example i needed
  • Fandi Susanto
    Fandi Susanto almost 5 years
    Error: EACCES: permission denied, open '/etc/letsencrypt/live/mysite.com/privkey.pem' how to solve?
  • Taersious
    Taersious over 4 years
    "You can't have SSL certificates on localhost." -- I have SSL working on my React app on localhost. Came here looking for how to make it work in Express. React is my frontend, and Express is my backend. Need it to work for Stripe, since my post to Stripe must be in SSL. Should be obvious, but in localhost I am testing, and on the server it will be production.
  • coolaj86
    coolaj86 over 4 years
    Correction: "You can't have valid SSL certificates on localhost".
  • Maddocks
    Maddocks over 4 years
    so the file mode is UTF8? the certificate and secret is written in 8 bit characters?
  • jhickok
    jhickok over 4 years
    Using sudo should be discouraged unless necessary. I just went through this process without using sudo, but I was logged in as admin on the machine.
  • javed
    javed over 3 years
    The above code is worked in my case I was faced "EACCES: permission denied, open '/etc/letsencrypt/live/domain.net/privkey.pem'” error. I was run sudo chown ubuntu -R /etc/letsencrypt and it's worked. ubuntu is user name you can replace it with user name.
  • Ryan
    Ryan about 3 years
    If I want to use variables instead of hard-coding paths like 'sslcert/server.key', I wonder how to get readFileSync working. See problem: stackoverflow.com/questions/56744208/…
  • Ryan
    Ryan about 3 years
    If I want to use variables instead of hard-coding paths like '/../certs/selfsigned.key', I wonder how to get readFileSync working. See problem: stackoverflow.com/questions/56744208/…
  • Ryan
    Ryan about 3 years
    If I want to use variables like PATH_TO_BUNDLE_CERT_1, I wonder how to get readFileSync working. See problem: stackoverflow.com/questions/56744208/…
  • ThN
    ThN almost 3 years
    My issue is that nodejs keeps telling me createServer is not function. my nodejs version is 11.15.0. Any idea?
  • ThN
    ThN almost 3 years
    My issue is that nodejs keeps telling me createServer is not function. my nodejs version is 11.15.0. Any idea?
  • ThN
    ThN almost 3 years
    My issue is that nodejs keeps telling me createServer is not function. my nodejs version is 11.15.0. Any idea?
  • ThN
    ThN almost 3 years
    actually I figured out my issue. I had this line const https = require('https').Server(app); and tried this https.createServer(options,app); That's when I kept getting createServer is not function error. Then, closely looking at examples like yours. I then I understood why I had issue. All I needed was this const https = require('https'); Thank you for your reply.
  • AlejandroDG
    AlejandroDG over 2 years
    NET::ERR_CERT_AUTHORITY_INVALID
  • Fiddle Freak
    Fiddle Freak over 2 years
    I'm also getting NET::ERR_CERT_AUTHORITY_INVALID when I try to make an http request(CRUD) using react. I think this is related to needing to setup a combined-ca, but I'm not sure how to do this...
  • kollein
    kollein over 2 years
    it works as expected, we need to open port on Linux as well. Thanks!