Given an SSL key and certificate, how does one create an HTTPS service?
-
2I used restify.js instead of express.js, but the idea is the same. Here's how I set up a node.js server that accepts both HTTP and HTTPS qugstart.com/blog/node-js/… – awaage Feb 28 '12 at 22:55
-
2without express and with the newest version of node - look here: stackoverflow.com/a/21809393/388026 – pkyeck Apr 9 '14 at 7:04
-
1What happened to this question? The answers imply that it was originally about express.js. – doug65536 Oct 4 '15 at 4:42
-
it's trivial to create a valid, self-signed SSL cert and launch an HTTPS server, just a few steps – Lloyd Dec 9 '15 at 21:26
-
1Its a bit late but if someone need a complete nodejs https tutorial, can find here: programmerblog.net/nodejs-https-server – Jason W Jun 10 '18 at 19:07
I found following example.
This works for node v0.1.94 - v0.3.1. server.setSecure()
is removed in newer versions of node.
Directly from that source:
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);
-
4
-
4
-
17This sample doesn't work anymore as the HTTPS implementation was re-done in Node.JS 0.4. See the corresponding docs at nodejs.org. stackoverflow.com/questions/5136353/… – scottyab Apr 2 '13 at 10:46
-
9This answer is very old and does not work anymore. Please see the answer by pkyeck below, or go to: nodejs.org/api/https.html – Jay Sheth Apr 8 '14 at 19:16
-
2
The Express API doc spells this out pretty clearly.
Additionally this answer gives the steps to create a self-signed certificate.
I have added some comments and a snippet from the Node.js HTTPS documentation:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
-
42Nice, was just about to post this myself. Thank you. Additionally, I found this article helpful for generating a self-signed certificate. – clayzermk1 Jan 18 '13 at 0:13
-
1Make sure you put
options
first inhttps.createServer
, to avoid cryptic errors. – wberry Jul 26 '13 at 16:20 -
1I am setting up an almost identical https server port 8888 and not sure how to change the routes. when I run curl curl --insecure localhost:8888 curl: (35) Unknown SSL protocol error in connection to localhost:8888 what is the error coming from and how to get around it. When I type localhost:8888 in the browser, it hangs and https:/localhost:8888 gives SSL error – reza Oct 25 '13 at 22:48
-
2@Costa you can redirect users from http to https with express-force-ssl or hand written middleware - it pretty straightforward – floatdrop Apr 6 '14 at 6:58
-
1
Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
-
Worked like a charm. This information came in very handy as I run a node.js tool (PDFJS) on top of a PHP app that was recently forced to run over https. The iframe was very unhappy to load my node.js app on an alternate, non-https port. – lewsid Oct 7 '14 at 16:12
-
1This looks good, but how can I generate the files you are requiring there (
*.pem
)? I tried following this page, but when openinglocalhost:8000
in the browser, no data is received (just loading...). – Ionică Bizău Feb 22 '15 at 20:03 -
6@IonicăBizău, for generating keys, install
openssl
, then in cmd prompt, typeopenssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3001
– mido Apr 6 '15 at 3:08 -
2@IonicăBizău you need to directly go to
https://localhost:8080
. HTTP is NOT HTTPS. – Dodekeract Aug 20 '15 at 14:52
The above answers are good but with Express and node this will work fine.
Since express create the app for you, I'll skip that here.
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});
-
This is technically the more correct answer, since the question was how to do it with Express.js – Kato Dec 20 '12 at 22:29
-
12This seems to be deprecated since "applications no longer inherit from http.Server" – Merlyn Morgan-Graham Jan 30 '13 at 9:59
-
1
-
1
-
1
The minimal setup for an HTTPS server in Node.js would be something like this :
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
If you also want to support http requests, you need to make just this small modification :
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
Update
Use Let's Encrypt via Greenlock.js
Original Post
I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:
- https://github.com/coolaj86/nodejs-ssl-example
- http://blog.coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
- https://github.com/coolaj86/nodejs-self-signed-certificate-example
Snippet:
var options = {
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
, requestCert: false
, rejectUnauthorized: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https
module handle it and then use that to serve you connect / express app.
Also, if you use server.on('request', app)
instead of passing the app when creating the server, it gives you the opportunity to pass the server
instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).
To enable your app to listen for both http
and https
on ports 80
and 443
respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express()
is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
- Download rar file for openssl set up from here: https://indy.fulgan.com/SSL/openssl-0.9.8r-i386-win32-rev2.zip
- Just copy your folder in c drive.
- Create openssl.cnf file and download their content from : http://web.mit.edu/crypto/openssl.cnf openssl.cnf can be put any where but path shoud be correct when we give in command prompt.
- Open command propmt and set openssl.cnf path C:\set OPENSSL_CONF=d:/openssl.cnf 5.Run this in cmd : C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
- Then Run OpenSSL> genrsa -des3 -out server.enc.key 1024
- Then it will ask for pass phrases : enter 4 to 11 character as your password for certificate
- Then run this Openssl>req -new -key server.enc.key -out server.csr
- Then it will ask for some details like country code state name etc. fill it freely. 10 . Then Run Openssl > rsa -in server.enc.key -out server.key
- Run this OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt then use previous code that are on stack overflow Thanks
var path = require('path');
var express = require('express');
var app = express();
var staticPath = path.join(__dirname, '/public');
app.use(express.static(staticPath));
app.listen(8070, function() {
console.log('Server started at port 8070');
});
-
3