Skip to main content

Provide SSL support over your http NodeJs-Express API

A simple HTTPS server using node.js:

Using ExpressJS and openssl, you can easily provide SSL support to your Api. For that you have to follow below given steps.
Steps to create a https server.
  1. Generate an SSL certificate with that key
  2. Create a app.js file
  3. Install express module
  4. Run to Test your app. :-)
  1. Generate an SSL certificate with that key:
For development purposes you can create a self-certified certificate.
First, generate a private key on linux-based system. It will store a 1024 bit RSA key in the file key.pem
openssl genrsa 1024 > key.pem
Then, generate an SSL certificate with that key:

openssl req -x509 -new -key key.pem > key-cert.pem

  1. Create a app.js file
var fs = require("fs"),                 //Requires fs module to read key, cert files
    express = require('express'),       // call express
    app = express(),                     // define our app using express
    http = require("http"),             //Get the http module
    https = require('https');           //Get the https module
var privateKey = fs.readFileSync("key.pem", 'utf8');        //load openssl generated privateKey
var certificate = fs.readFileSync('key-cert.pem', 'utf8');  //load openssl generated certificate
var credentials = {key: privateKey, cert: certificate};     //create credentials object to create ssl
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();                 // get an instance of the express Router
// middleware to use for all requests
router.use(function (req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/
router.get('/', function (req, res) {
    res.end("<div><h1>Hello</h1></div>")
});
app.use('/', router);
//Create http and https server using app settings
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

//http server listen all request of 8080 port
httpServer.listen(8080, function () {
    "use strict";
    console.log('Magic happens on port ' + 8080);
});
//http server listen all request of 8080 port
httpsServer.listen(8089, function () {
    "use strict";
    console.log('Magic SSL happens on port ' + 8089);
});

  1. Install express module
I have use express module to show this demonstration. You can download express module either using npm install express --save command or you can first define dependencies in package.json and run npm install command to download express module.

Create package.json along with app.js
{
    "name": "http-demo",
    "main": "app.js",
    "dependencies": {
        "express": "~4.0.0"
    }
}

Open terminal and type $npm install
  1. Run to Test your app. :-)
Now run your app.js uing command $node app.js

You can see output like on your terminal
/opt/node-v0.10.28-linux-x64/bin/node app.js
Magic happens on port 8080
Magic SSL happens on port 8089

To test app, open your browser and type https://localhost:8089/

You can download the working code from : https://github.com/deepakshrma/https_demo
Directory structure of the app

Comments

Popular posts from this blog

Introduction to Node.js - Part-1 Node Command line Interface(CLI) App

Aim This document is get to start with the Node.Js. This is a simple introduction to Node and Its corresponding frameworks. This will help you to create a simple chit chat server application using node.js, express.js and socket.io. I have used the chat demo app of socket.io to learn you node. Introduction to Node.Js CLI Introduction to Node If you are from the Java and .net background. You might have create several JSP and ASP application to learn Java and ASP web framework. While create web app. You also learned JavaScript to interact with the HTML dom elements. If you go to the wikipedia definition of node which is “ Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, and IBM_i ”. It tells that Node is a framework where you can write code in Javascript programming language on s

Loading- Exporting Modules in Node.Js

Loading a module: In node you can load module either using the path to the module or giving name  of the module. require keyword is used to load  module in node. Its look for the file in given path to load module if the require module is not core node module. You can install third party module using NPM (Node Package Manger). It downloads from the global repository to your local machine. var module = require( 'module-name' ); The require function returns an object that represent the module which have exported. It can be any javascript data type. It could be function, an array, any javascript object. Exporting a module: The CommonJs Module system is use to share the object or properties in node.js. Since Javaascript runs program in global scope. CommonJs Module is one of the best way for creating and sharing namespace in the javascript environment. Here below given an example to export a function in node.js. //person.js /** * Created by deepak.m.shrma@gm