Javascript – Express (node.js) using HTTPS and HTTP

expresshttphttpsjavascriptnode.js

I am using the express (3.0) framework on node.js to route my application.

Most of my application uses the http protocol however there is one specific route I want to serve via https only. This is the part of my API which is responsible for registering and authenticating users.

for example:

app.get('/connect', function(req, res){
 // Must be on HTTPS, if not redirect to HTTPS
});

app.post('/connect', function(req, res){
  // Must be on HTTPS
});

app.get('/', function(req, res){
 // Must be on HTTP
});

app.get('/build', function(req, res){
 // Must be on HTTP
});

How does one facilitate using both within the same application? I am struggling to find any examples of this in the wild.

Best Answer

Simply pass your app (which is really a request handler function) to the createServer of http and https.

var express = require('express')
    , http = require('http')
    , https = require('https')
    , app = express();

http.createServer(app);
https.createServer({ ... }, app);

Both HTTP and HTTPS requests get routed through the same Express app. In a route handler, to check whether a request was made over https, use req.secure.

app.get('/route', function(req, res) {
    if (req.secure) {
        ...
    } else {
        res.redirect(301, 'https://example.com/route');
    }
});

As a side note, modern wisdom considers mixed http/https sites insecure. You may protect the user's password by requiring them to log in over SSL, but then switching back to http for subsequent requests makes it trivial for an attacker to steal a user's login cookie.

Consider making all requests by logged-in users over SSL.