user1775718
user1775718

Reputation: 1578

Using https on heroku

I'm trying to get my app on heroku to be 'https everywhere'. So far the app is like this:

"use strict";

console.log('working');

//Initial setup
var path, https, privateKey, certificate, port, cdjshelp, util, cookies, oauth, twitter, crypto, _, options, express, auth, lodash, dust, dustjs,
    dustjsHelpers, commonDustjsHelpers, app, db, fs, mongoose, mongooseTimes, Comment, Bird, Sighting, Site, User,
    Backbone, io;

//node modules, express and dust declarations
path = require('path');
util = require('util');
fs = require('fs');
https = require('https');
privateKey = fs.readFileSync('./config/privatekey.pem').toString();
certificate = fs.readFileSync('./config/certificate.pem').toString();
crypto = require('crypto');

//APP Defn...
app = require('./config/appSetup')(dustjs);

//******** SERVER CONFIG **********//
var port = process.env['PORT'] = process.env.PORT || 4000; // Used by https on localhost

options = {
    key: privateKey,
    cert: certificate
}

https.createServer(options, app).listen(port, function() {
    console.log("Express server listening with https on port %d in %s mode", this.address().port, app.settings.env);
});

I've used the openSSL CLI to generate a privatekey.pem and a certificate.pem and loaded them as options.

I know that heroku has a procedure if you're using DNS records to have the app serve to your own domain. I know that you have to go through the procedure listed here. I'm not remapping any urls or altering any records - my url is birdsapp.heroku.com.

Heroku uses piggyback SSL, so if you setup an http server your app will respond to https requests without any additional config. The problem there is that the http routes are still available, so I've stuck to setting an https server only - but it's timing out with nothing in the logs, so I think that there's a problem with the SSL setup.

Is the above setup correct? Is that the best way to do basic https server on heroku?

Upvotes: 0

Views: 1032

Answers (1)

user1775718
user1775718

Reputation: 1578

OK, it's actually much simpler than that...

You simply create an http server:

//******** SERVER CONFIG **********//
var port = process.env['PORT'] = process.env.PORT || 4000;

http.createServer(app).listen(port, function() {
    console.log("Express server listening with http on port %d in %s mode", this.address().port, app.settings.env);
});

and add a route redirect:

app.all('*', function(req, res, next) {
    if (req.headers['x-forwarded-proto'] != 'https')
        res.redirect('https://' + req.headers.host + req.url)
    else
        next() /* Continue to other routes if we're not redirecting */
});

heroku takes care of the rest, setting up an http server which is a mirror of your http server and uses their certs, etc.

Upvotes: 1

Related Questions