ApplePie
ApplePie

Reputation: 1185

How do I enable all my routes to have https and force http to https?

I do not understand how I can force all my routes to have https and always force http to https. Can anyone advice on how I should change my code below? I am still new to node.js. Any help would be very much appreciated.

index.js

const express = require('express');
const hbs = require('hbs');
const path = require('path');
var morgan = require('morgan')
var session = require('express-session')
const MongoStore = require('connect-mongo')(session);
var passport = require('passport')
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/sth');

const mainMiddleware = require('./middleware/main.js');
const port = process.env.PORT || 3000;
var app = express();
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

app.use(session({
    secret: 'alsjbfkajsbef09876', //salt
    resave: false, // always re-init cookie
    saveUninitialized: false, // always create session even if not log in
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}))
app.use(passport.initialize());
app.use(passport.session());

app.use('/public', express.static(path.join(__dirname,'public')));

app.set('view engine', 'hbs');

app.use(mainMiddleware);

app.get('/', function (req, res) {
    let loginStatus = req.isAuthenticated() ? "DASHBOARD" : ""
    let dashboard = req.isAuthenticated() ? "/client/current" : "/"
    res.render('frame.hbs', {content: 'homeContent', css: 'home.css', dashboard, loginStatus, script: ['online-tracking.js']})
})

//----include routes
app.use('/api', require('./routes/api'));
app.use('/', require('./routes/page'));
app.use('/client', require('./routes/client-page'));
app.use('/admin', require('./routes/admin-page'));


//----connecting to port
app.listen(port,()=>{
    console.log(`success connection to port ${port}`);
})

Upvotes: 4

Views: 454

Answers (3)

tremor
tremor

Reputation: 3186

With greenlock-express (available on NPM) this is super easy, and it also hooks you up with an SSL Cert from LetsEncrypt. Here is there example script from the docs. https://git.coolaj86.com/coolaj86/greenlock-express.js

'use strict';

require('greenlock-express').create({

  // Let's Encrypt v2 is ACME draft 11
  version: 'draft-11'

  // Note: If at first you don't succeed, switch to staging to debug
  // https://acme-staging-v02.api.letsencrypt.org/directory
, server: 'https://acme-v02.api.letsencrypt.org/directory'

  // Where the certs will be saved, MUST have write access
, configDir: '~/.config/acme/'

  // You MUST change this to a valid email address
, email: '[email protected]'

  // You MUST change these to valid domains
  // NOTE: all domains will validated and listed on the certificate
, approveDomains: [ 'example.com', 'www.example.com' ]

  // You MUST NOT build clients that accept the ToS without asking the user
, agreeTos: true

, app: require('express')().use('/', function (req, res) {
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.end('Hello, World!\n\nšŸ’š šŸ”’.js');
  })

  // Join the community to get notified of important updates
, communityMember: true

  // Contribute telemetry data to the project
, telemetry: true

//, debug: true

}).listen(80, 443);

Since I tried this - it's been the foundation of every node/express site I've built.

Prior to finding this, I would actually use Apache as a front-end proxy for node. You may find this to be preferable still anyway, if you wish to bind your site to port:443 in a virtualhosting environment.

What I really like about greenlock is that you bind port:80 and port:443 in the init script and it also handles the redirect for you.

Upvotes: 1

Sushant Magoo
Sushant Magoo

Reputation: 374

Try including this code in your Express project

var http = require('http');
var https = require('https');
app.set('port', port);
app.set('secPort', port + 443);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
var options = {
    key: fs.readFileSync('/private.key'),
    cert: fs.readFileSync('/certificate.pem')
 };
var secureServer = https.createServer(options, app);
secureServer.listen(app.get('secPort'), () => {
    console.log('server listening on port', app.get('secPort'));
});
secureServer.on('error', onError);
secureServer.on('listening', onListening);
app.all('*', (req, res, next) => {
    if (req.secure) {
        return next();
    } else {
        res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
    }
});

Upvotes: 0

Björn Rave
Björn Rave

Reputation: 119

If you want to have your connections encrypted with https you need a SSL-certificate to verify, that you are a real human an pledge for your content. Most of the hosting services like Microsoft Azure and Amazon Web Services offer a possibility to create a SSL-certificate

Upvotes: 0

Related Questions