I'd like to encrypt my Koa server with SSL. It seems simple enough with a regular httpServer, but I'm not how to do it with Koa. Could anyone help?
Asked
Active
Viewed 1.2k times
12
-
1@Rob Koa is a web framework (like express) rather than a web server (like Nginx or Apache). No documentation exists on configuring it directly with HTTPS (rather than running a server on top). Please at least try to read my question before making such a vicious, unproductive comment. – Taconut Jun 23 '17 at 22:12
-
Then I confused it with a server I once knew however the rest of my comment still stands – Rob Jun 24 '17 at 02:47
-
1Not really. It doesn't even look like there's a way to set up SSL on Koa.js. I checked through the documentation like three times over and there's literally no way to do it. I ended up actually going into Koa's source code and modifying that. So no, your comment doesn't really stand. Please try to refrain from making those sorts of comments on subjects you know absolutely nothing about. – Taconut Jun 25 '17 at 17:48
2 Answers
19
I stumbled upon this. Launching an https server with the node package and passing it the Koa
server instance .callback()
does the trick.
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var Koa = require('koa');
var server = new Koa();
// add main routes
// the following routes are for the authorisation challenges
// ... we'll come back to this shortly
var acmeRouter = require('./acme-router.js');
server
.use(acmeRouter.routes())
.use(acmeRouter.allowedMethods());
var config = {
domain: 'example.com',
http: {
port: 8989,
},
https: {
port: 7979,
options: {
key: fs.readFileSync(path.resolve(process.cwd(), 'certs/privkey.pem'), 'utf8').toString(),
cert: fs.readFileSync(path.resolve(process.cwd(), 'certs/fullchain.pem'), 'utf8').toString(),
},
},
};
let serverCallback = server.callback();
try {
var httpServer = http.createServer(serverCallback);
httpServer
.listen(config.http.port, function(err) {
if (!!err) {
console.error('HTTP server FAIL: ', err, (err && err.stack));
}
else {
console.log(`HTTP server OK: http://${config.domain}:${config.http.port}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTP server\n', ex, (ex && ex.stack));
}
try {
var httpsServer = https.createServer(config.https.options, serverCallback);
httpsServer
.listen(config.https.port, function(err) {
if (!!err) {
console.error('HTTPS server FAIL: ', err, (err && err.stack));
}
else {
console.log(`HTTPS server OK: http://${config.domain}:${config.https.port}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTPS server\n', ex, (ex && ex.stack));
}
module.exports = server;
-
Thanks a bunch for taking the time to answer this even though I solved my own issue! I'll definitely use this trick in the future! – Taconut Jul 28 '17 at 00:16
2
Looks like there's no clear cut way to do this, but running Nginx on top of my server was an easy workaround.

Taconut
- 951
- 4
- 10
- 29