How to run a https website with Nodejs, express and socket.io


Step 1: generate RSA key
Use command line: (on Windows we can use Cygwin)

openssl genrsa 1024 > file.pem

Result:

$ openssl genrsa 1024 > file.pem
Generating RSA private key, 1024 bit long modulus
...............................................++++++
................++++++
e is 65537 (0x10001)

Step 2: create file csr.pem

openssl req -new -key file.pem -out csr.pem

Result:

$ openssl req -new -key file.pem -out csr.pem
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
CCountry Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New-york
Locality Name (eg, city) []:Buffalo
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Toturialspots JSC
Organizational Unit Name (eg, section) []:Community
Common Name (e.g. server FQDN or YOUR name) []:toturialspots.com
Email Address []:toturialspots@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:xxxxxxxxxxxx
An optional company name []:

Step 3: create SSL certificate file

openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.crt

Result:

$ openssl x509 -req -days 365 -in csr.pem -signkey file.pem -out file.crt
Signature ok
subject=/C=US/ST=Newyork\x1B[D\x1B[D\x1B[D\x1B[D-york/L=B\xC3\x83uffalo/O=Tutorialspots JSC/OU=Community/CN=tutorialspots.com/emailAddress=toturialspots@gmail.com
Getting Private key

Note: this is in practice, in production you must buy one certificate or use free SSL

Step 4: continue with Nodejs app
here an example app:
app.js

var fs = require('fs');
var express = require('express'); 
var options = {
  key: fs.readFileSync('./file.pem'),
  cert: fs.readFileSync('./file.crt')
};

var app = express.createServer(options);  

var serverPort = 33443;
 
var io = require('socket.io').listen(app);
 
app.get('/', function(req, res) {
  res.sendfile('/public/index.html' ,{root: __dirname});
});
 
io.on('connection', function(socket) {
  console.log('new connection');
  socket.emit('message', 'This is a message from the dark side.');
});
 
app.listen(serverPort, function() {
  console.log('server up and running at %s port', serverPort);
});

public/index.html

<!doctype html>
<html>

  <head>

  </head>
  <body>
    <h1>I am alive!!</h1>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.js"></script>

    <script>
      var URL_SERVER = 'https://tutorialspots.com:33443';
      var socket = io.connect(URL_SERVER);

      socket.on('message', function(data) {
        alert(data);
      });
    </script>
  </body>

</html>

Update: 3/27/2023
For Socket.io 4.6.1 and Express 4.18.2:

var fs = require('fs');
var express = require('express'); 
var si = require('socket.io')
var options = {
  key: fs.readFileSync(__dirname+'/domain.com.key'),
  cert: fs.readFileSync(__dirname+'/domain.com.cert')
};
 
var app = express();  
const server = require('https').createServer(options,app);
 
var serverPort = 33443;
  
var io = si(server,{
  cors: {
    origin: "*",
    methods: ["GET", "POST"],    
    credentials: true
  }
});
  
app.get('/', function(req, res) {
  res.end()
});
  
io.on('connection', function(socket) {
  console.log('new connection');
  socket.emit('message', 'This is a message from the dark side.');
});
  
server.listen(serverPort, function() {
  console.log('server up and running at %s port', serverPort);
});

1 Comment

Leave a Reply