How to Create an Https Server in Node.Js

How to create an HTTPS server in Node.js?

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`)
};

Create an HTTPS server with Node.js

try with:

openssl genrsa -out key.pem 1024

or

openssl genrsa -out key.pem 2048

A key size of 512 is considered weak

how to make my node.js server https instead of http

Developing locally in HTTPS is not common. How did you issue your cert and for what domains? Will the browser recognise your cert as coming from an SSL certificate authority? Despite your best intentions you might still get the insecure connection screen in your browser.

A popular option today is to do all of your development with HTTP. Then you use a reverse proxy like Cloudflare or an AWS load balancer in front of your server. Your users then connect and negotiate an SSL connection with the proxy which in turn will talk to your server over HTTP.

Setting this up is easy. You simply allow Cloudflare to manage your DNS and it will automatically route all connections through its servers over SSL before passing it onto your node application. This will give your website the nice secure lock icon.

Once you know more, you can also encrypt traffic between Cloudflare and your server.

How to make an HTTP/HTTPS request within a Node.js server?

Server code:

var http = require('http');
var https = require("https");

var server = http.createServer(function (req, res) {

let call = new Promise((resolve, reject) => {

var options = {
host: "jarrenmorris.com",
port: 443,
path: '/gamesense/r6_db/1.json'
};

https.get(options, function (res) {

var bodyChunks = [];

res.on('data', function (chunk) {
bodyChunks.push(chunk);
}).on('end', function () {
resolve(Buffer.concat(bodyChunks));
});

}).on('error', function (e) {
reject(e);
});

});

call.then((data) => {

// do something here with the successful request/json

res.writeHead(200, {
'Content-Type': 'text/plain'
});

res.end(data);

}).catch((err) => {

// do something here with the failure request/json
// res.write("ERROR:");
res.end(err);

});

});

server.listen(8081, "127.0.0.1", () => {
console.log(`Server listen on ${server.address().address}:${server.address().port} `);
});

Response:

{"name":"tim","age":"42"}

First thing i noticed, while i tried to run your code was, you cant establish a connection to your node.js.

The reason for this was you use the https module, but didnt specify an certificates/keyfiles. Skip this, and work with http till you get the result you want.

Then i wrapped you https request to the external api/file in a promise.
This allows a simple chaining and better readability of the code.

When the promises resolves/fullfill, we answer the request on the http server with the data we received from the external request.

The res.end in your code (where you put it) made no sense, since you didnt wait for the external request to complete. Thats the reason why its nothing is shown in the browser window.

Node.js + Express.js | Trying to set up a HTTPS server

Try mention you key's passphrase in this line or provide an empty string '':

const credentials = {key: privateKey, cert: certificate, passphrase: '??'};

Node.js https server for localhost

That (and others also) article contains bug that happen I guess only for latest version of node.js.

You need add encoding options while reading files {encoding: "utf8"} as below:

https.createServer({
key: fs.readFileSync('server.key', {encoding: "utf8"}),
cert: fs.readFileSync('server.cert', {encoding: "utf8"})
}, app).listen(17001, () => {
console.log('Listening...')
})

NodeJS add SSL to HTTPserver

Use https library instead of http:

const https = require('https');
const fs = require('fs');
const privateKey = fs.readFileSync('./localhost.key', 'utf8');
const certificate = fs.readFileSync('./localhost.crt', 'utf8');

const credentials = {
key: privateKey,
cert: certificate,
};

const httpsServer = https.createServer(credentials, this.app);

The self-signed cert can be generated like so:

openssl req -x509 -out localhost.crt -keyout localhost.key \
-newkey rsa:2048 -nodes -sha256 \
-subj '/CN=localhost' -extensions EXT -config <( \
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

See https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates for more info.



Related Topics



Leave a reply



Submit