How to Generate Free SSL certificates in node.js

We will utilize let’s encrypt’s greenlock-express, a node.js library that handles generating ssl certificates for us.

  1. install
npm install letsencrypt-express --save

2. Put those code in your node.js app

function approveDomains(opts, certs, cb) {

if (certs) {
opts.domains = certs.altnames;
}
else {
opts.domains = opts.domains; // each time a page has been visited, this function will be called and pass in the domain being used to visit this page; here we just assume all domains are fine, and this will generate certs for every domain the user used to visit this page
opts.email = "skycloud112@gmail.com";
opts.agreeTos = true;
}

cb(null, { options: opts, certs: certs });
}

var lex = require('letsencrypt-express').create({
// NOTE, server should be set to 'staging' while testing
server: 'https://acme-v01.api.letsencrypt.org/directory'
, challenges: { 'tls-sni-01':
require('le-challenge-sni').create({ webrootPath: '~/letsencrypt/var/acme-challenges' })
}
, challengeType: 'tls-sni-01'
, store: require('le-store-certbot').create({
configDir: '/etc/letsencrypt',
privkeyPath: ':configDir/live/:hostname/privkey.pem',
fullchainPath: ':configDir/live/:hostname/fullchain.pem',
certPath: ':configDir/live/:hostname/cert.pem',
chainPath: ':configDir/live/:hostname/chain.pem',
workDir: '/var/lib/letsencrypt',
logsDir: '/var/log/letsencrypt',
webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge',
debug: false
})
, approveDomains: approveDomains
});
//handles acme-challenge and redirects to https
require('http').createServer(lex.middleware(require('redirect-https')())).listen(80, function () {
console.log("Listening for ACME http-01 challenges on", this.address());
});

require('https').createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () {
console.log("Listening for ACME tls-sni-01 challenges and serve app on", this.address());
});

It will create a auto-direct at 80 port for http. When user visit http://yoursite.com, it will automatically be directed to https://www.yoursite.com

Alternative

The first way automatically generate the certificates. We can manually get free certificates too via https://www.sslforfree.com/.

When you have followed the steps at sslforfree.com, you will get 3 texts: private key, certificate and ca bundle. Put each of those text in one file, like this:

Then, you can use those with express:

var options = {
key: fs.readFileSync(path.resolve(__dirname, 'ssl/steve.mu.key')),
cert: fs.readFileSync(path.resolve(__dirname, 'ssl/steve.mu.crt')),
ca: fs.readFileSync(path.resolve(__dirname, 'ssl/steve.mu.ca'))
};
var PORT = 443;
var server = https.createServer(options, app);
server.listen(PORT, function () {
console.log(`server at port ${PORT}`);
});
Like what you read? Give Steve Mu a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.