Search code examples
sslhttpsopensslssl-certificatenodejs-server

How to host a HTTPS server with a valid certificate in Node.js using HTTPS library


I want to host my own https server, but the certificate I have generated is not valid, and when accessing from broswers it says insecure connection.


Solution

  • You can either implement it in your NodeJS code base or go with http proxy using Nginx or Apache

    Using code from this answer:

    http = require("http");
    
    var privateKey = fs.readFileSync('privatekey.pem').toString(); var
    certificate = fs.readFileSync('certificate.pem').toString();
    
    var credentials = crypto.createCredentials({key: privateKey, cert:
    certificate});
    
    var handler = function (req, res) {   res.writeHead(200,
    {'Content-Type': 'text/plain'});   res.end('Hello World\n'); };
    
    var server = http.createServer(); server.setSecure(credentials);
    server.addListener("request", handler); server.listen(8000); ```
    

    It's recommended using the Nginx method

    https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04

    Add the SSL files in the Vhost

    If you want to go with a free SSL try certbot, it will auto-install SSL in the vhost

    https://certbot.eff.org/