Given an SSL key and certificate, how does one create an HTTPS service?
To start your https server, run node app. js (here, app. js is name of the file) on the terminal. or in your browser, by going to https://localhost:8000 .
By simply installing the Express NodeJS package and creating a simple configuration script, you can have a secure web service running over HTTPS.
key and . crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server. var https = require('https'); var fs = require('fs'); var express = require('express'); var options = { key: fs.
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);
For Node 0.3.4 and above all the way up to the current LTS (v16 at the time of this edit), https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener has all the example code you need:
const https = require(`https`); const fs = require(`fs`); const options = { key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`), cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`) }; https.createServer(options, (req, res) => { res.writeHead(200); res.end(`hello world\n`); }).listen(8000);
Note that if want to use Let's Encrypt's certificates using the certbot tool, the private key is called privkey.pem
and the certificate is called fullchain.pem
:
const certDir = `/etc/letsencrypt/live`; const domain = `YourDomainName`; const options = { key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`), cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`) };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With