How to use OpenSSL self-signed certificate for Nodejs apps

copyright : wikipedia

To secure your node.js apps (web site or API ) we need to configure SSL Certificate. Here are the steps to create and configure a new self-signed certificate for express web server.

Install  OpenSSL

  • extract it to your folder. For example , C:\dg-tools\openssl-0.9.8k_X64\

Generate a 2048 RSA Private key

  • Run the following command to create private key
C:\dg-tools\openssl-0.9.8k_X64\bin>openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

You may receive an error unable to load config file openssl.cnf

Navigate to c:\openssl\ssl\ bin> and check whether openssl.cnf file is available , if not , then copy it  from C:\dg-tools\openssl-0.9.8k_X64\bin

  • Rerun command with specifying configuration file and enters required information to create private key
C:\dg-tools\openssl-0.9.8k_X64\bin>openssl req -config "C:\openssl\ssl\openssl.cnf" -new -newkey rsa:2048 -nodes -out certreq.txt -keyout private.key

 When the key generation is done it will create key.prem and csr.prem

  • Sign your certificate with newly created private key.
C:\dg-tools\openssl-0.9.8k_X64\bin>openssl x509 -req -days 365 -in csr.pem -signkey key.pern -out server.crt 

The “server.crt” file will be created.

That’s it. Your self-signed certificate is ready to configure your site.

Configure your Webserver (express) with openSSL certificate.

  • Here is code snippet that shows how to configure a ssl certificate for express web server.

var fs = require('fs')

  var https = require('https')
    // set up the express server.
    const app = express();
    // Enable CORS for all apis

    app.all("/*", (_req, res, next) => {

        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "POST, GET");
        res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-Correlation-Id");

    const resourceRoot = path.resolve(process.cwd(), args.resources);
    app.use("*", (_req, resp) => {
    resp.sendFile(path.resolve(args.resources, "index.html"));
    // Run the server...
    app.set("port", args.port);
    const announce = () => console.log(`***** WebServer listening on http:localHost:${app.get("port")}, resource root is ${resourceRoot}`);

   https.createServer({key: fs.readFileSync('key.prem’),

     cert: fs.readFileSync('server.cert')

    }, app).listen(app.get("port"), announce);

  • Make sure that your express server is returning promises.

Start your web server (express)

(Make sure that you have placed key.prem and server.crt in app root direct )

npm run start