Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Installing SSL On Socket.IO Node.js

Installing SSL On Socket.IO Node.js

Problem

I bought GoDaddy Standard SSL Certificate and installed it on http://mysite.com. Now https://mysite.com works well.

Now, I want to install the certificate for socket.io which is running at http://mysite.com:3000

I tried to connect with SSL by doing:

var socket = io.connect('https://www.mysite.com:3000', {secure:true}); 

but it's not working. Here is the server.js

var io = require('socket.io'), 
    connect = require('connect'), 
    mysql = require('mysql');

var app = connect().use(connect.static('../public_html/node/'));
app.listen(3000);
var server = io.listen(app);
server.sockets.on('connection', function(socket) { 
     socket.emit('getid', {message: "A New user is online"});
}

and the client index.html

Any suggestions?

Problem courtesy of: Praveen

Solution

Your clients are connecting to http, try having your client index.html connect to https.

Additionally, you need to load a certificate.

const crypto = require('crypto'),
  fs = require("fs"),
  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);

Create your self-signed .pem files. (For bonus points, get your .csr signed by a reputable company.)

openssl genrsa -out privatekey.pem 2048 
openssl req -new -key privatekey.pem -out certrequest.csr 
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
Solution courtesy of: jnovack

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Installing SSL On Socket.IO Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×