user3293156 user3293156 - 1 year ago 162
Javascript Question

Get restify REST API server to support both HTTPS and HTTP

I am using node.js restify ver4.0.3

The simple following code works as a simple REST API server that supports HTTP. An example API call is

var restify = require('restify');

var server = restify.createServer({
name: 'myapp',
version: '1.0.0'

server.get('/echo/:name', function (req, res, next) {
return next();

server.listen(9898, function () {
console.log('%s listening at %s',, server.url);

Suppose I want to support HTTPS and make the API call

How can this be done?

I noticed that restify code changes pretty fast and older code with older version may not work with the latest version.

Answer Source

To use HTTPS, you need a key and a certificate:

var https_options = {
  key: fs.readFileSync('/etc/ssl/self-signed/server.key'),
  certificate: fs.readFileSync('/etc/ssl/self-signed/server.crt')
var https_server = restify.createServer(https_options);

You will need to declare the same route twice (create a custom function for it), for allowing both HTTP and HTTPS access:

http_server.listen(80, function() {
   console.log('%s listening at %s',, http_server.url);
https_server.listen(443, function() {
   console.log('%s listening at %s',, https_server.url);

To configure routes to server, and redirect between them as needed:

http_server.get('/1', function (req, res, next) {
    res.redirect('', next);
https_server.get('/1', function (req, res, next) {
    // Process the request   

The above listens to requests to a route /1 and simply redirects it to the HTTPS server which processes it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download