Skip to content

Instantly share code, notes, and snippets.

@jonathandavidlewis
Last active December 20, 2017 20:51
Show Gist options
  • Save jonathandavidlewis/ebe4c4c0375ea3e497780063a524d9fe to your computer and use it in GitHub Desktop.
Save jonathandavidlewis/ebe4c4c0375ea3e497780063a524d9fe to your computer and use it in GitHub Desktop.
How to setup https on a Node server

How to Setup Https on a Node server

Before

const app = require('./server.js');
const http = require('http');
const port = process.env.PORT || 8080;

const server = http.createServer(app);

server.listen(port, () => console.log('Listening on port:', port));

We are going to:

  1. install Let's Encrypt
  2. Run CertBot
  3. change ownership of the files
  4. Associate filepaths with the cert and private key
  5. Add the https server code.
  6. Add an Http redirect to https

Install CertBot

https://startupnextdoor.com/how-to-obtain-and-renew-ssl-certs-with-lets-encrypt-on-node-js/
download CertBot: wget https://dl.eff.org/certbot-auto
change permissions: chmod a+x certbot-auto

Run CertBot

Verify your server is NOT running.
Verify incoming requests on 443 can get through (Check your port forwarding and security settigns if needed)
./certbot-auto certonly --standalone -d yourdomain.example.com
Follow the prompts

Change ownership of the cert files

How to change file ownership in Ubuntu like this: sudo chown -R username:group directory We will use: sudo chown -R ubuntu /etc/letsencrypt/live
Changes ownership to Ubuntu so node can run under the Ubuntu user and have access to those files.

After

const app = require('./server.js');
const http = require('http');
const https = require('https');
const port = process.env.PORT || 8080;
const httpsPort = process.env.HTTPS_PORT || 8443;
const fs = require('fs');

const credentials = {
  key: fs.readFileSync('privkey.pem'),
  cert: fs.readFileSync('fullchain.pem')
};

const httpsServer = https.createServer(credentials, app);

const httpsRedirect = http.createServer((req, res) => {
  res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url }).end();
});

httpsRedirect.listen(port, () => console.log('http listening on port:', port, 'to redirect to https'));

httpsServer.listen(httpsPort, () => console.log('https listening on port:', httpsPort));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment