Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an HTTPS server in Node.js?

Given an SSL key and certificate, how does one create an HTTPS service?

like image 353
murvinlai Avatar asked May 13 '11 23:05

murvinlai


People also ask

How do I start node server with HTTPS?

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 .

Can you create an HTTPS Web service with node js?

By simply installing the Express NodeJS package and creating a simple configuration script, you can have a secure web service running over HTTPS.

How do I run HTTPS on localhost node js?

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.


2 Answers

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); 
like image 157
Jacob Marble Avatar answered Sep 23 '22 23:09

Jacob Marble


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`) }; 
like image 42
hvgotcodes Avatar answered Sep 26 '22 23:09

hvgotcodes