How to automatically reload updated SSL certificates in Node.js Application

You can use the flag --post-hook to restart your application after every renewal.

certbot renew --post-hook "pm2 restart app_name"
Update #1

Please note that the command we are running is in crontab and any global program has to be referenced with the full path. You can use the which command to find the executable file path for the command.


You can reload the new certs without restarting your server.

According to the issue Reload certificate files of https.createServer() without restarting node server #15115 , specifically this comment from mscdex:

FWIW you can already do this with SNICallback():

const https = require('https');
const tls = require('tls');
const fs = require('fs');
var ctx = tls.createSecureContext({
  key: fs.readFileSync(config.sslKeyPath),
  cert: fs.readFileSync(config.sslCrtPath)
});
https.createServer({
  SNICallback: (servername, cb) => {
    // here you can even change up the `SecureContext`
    // based on `servername` if you want
    cb(null, ctx);
  }
});

With that, all you have to do is re-assign ctx and then it will get used for any future requests.

Using the example above, you just need to do fs.readFileSync again on the cert path from within the SNICallback and attach them to the ctx object. But, you only want to do this when you know they've just changed. You can watch the files from javascript for changes. You can use fs.watch() for that or something from npm.