Implementing virtual hosts and HTTPS encryption

Is it possible to configure vhosts on Express with https? This is my current code without SSL:

var express = require('express');
var vhost = require('vhost');
var path = require('path');

var appOne = express();
var appTwo = express();
var appVhosts = module.exports = express();

appOne.use(express.static(path.join(__dirname, 'pages')));

appTwo.get('/', function(req, res){
    res.send('That service isn't up right now!')
});

app.use(vhost('siteone.com', appOne));
app.use(vhost('sitetwo.com', appTwo));

appVhosts.listen(80);

However, I believe that the https module only accepts one ssl cert at a time.

Answer №1

It turns out that the https.Server class actually inherits from tls.Server, which gives access to a helpful method called addContext(). This method allows you to set up multiple certificates for your server. I even created a small package specifically designed to utilize this feature and achieve the desired outcome. You can take a look at my implementation by visiting https://www.npmjs.com/package/vhttps.

Answer №2

To ensure secure connections for each application, you must define SSL Options and assign them accordingly:

// (A) Reading SSL files
var fs = require('fs');
var appOneSSLOps = {
  key:  fs.readFileSync('./path_to_file/private.key'),
  cert: fs.readFileSync('./path_to_file/certificate.crt')
}
var appTwoSSLOps = {
  key:  fs.readFileSync('./path_to_file/private2.key'),
  cert: fs.readFileSync('./path_to_file/certificate2.crt')
}

// (B) Assigning SSL files to corresponding apps
var https = require('https');
var appOneServer = https.createServer(appOneSSLOps , appOne).listen(443);
var appTwoServer = https.createServer(appTwoSSLOps , appTwo).listen(80);

// (C) Redirecting Port 80 to 443 - > Manually or using child_process on Linux Ubuntu:
childProcess = require('child_process');
var optionExec = {timeout: 3000}; //options for childProcess.exec
childProcess.exec(
  'sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 443',
  optionExec,
  function(err, stdout, stderr) {

  }
);

// (D) Enforcing HTTPS - Assuming appOne is the main application.
appOne.use(function(request, response, next) {
  if(!request.secure) {
    response.redirect('https://' + request.headers.host + request.url);
  }
  next();
});

Note: This setup assumes that appOne serves as the main application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating dynamic email content with Node.js using SendGrid templating

How can I properly format SendGrid's content using Node.js? I'm currently working on sending emails from a contact form within an application using SendGrid. I have a Google Cloud Function set up that I call via an HTTP post request. Although I ...

Deliver integers using Express.js

When I try to send a response with Express using the code below, it doesn't work: res.send(13245) An error message is displayed: express deprecated res.send(status): Use res.sendStatus(status) instead src/x.js:38:9 (node:25549) UnhandledPromise ...

Experiencing unexpected 502 Bad Gateway errors from AWS API Gateway following an update to Lambda runtime from Node 8.x to Node 12.x

After transitioning our staging environment for the REST API from NodeJS 8.x to NodeJS 12.x on AWS Lambda due to end of life for NodeJS 8.x runtime, we have encountered a new issue. Periodically, requests from our frontend web app to API Gateway fail with ...

The method for accessing instance variables from any location within a node.js class

I'm currently working on an application using node.js and postgresql, leveraging the express framework. I aim to adhere to the MVC design pattern as closely as possible. My objective is to generate query results within a model class and then pass the ...

Should I share a single DB connection throughout the entire app or establish a new connection to the DB for each request?

I am currently working on developing an API using Nodejs and Restify. My database of choice is MongoDB, with the use of Mongoose. One question that has been on my mind is whether it would be better to share a database connection throughout the entire appl ...

Having trouble downloading files in React and Node.js

I need to retrieve a specific file from the uploads folder and download it into my download folder. Both folders are located in the same directory, and the file's name is BasicUserFile-id.jpg. On my second attempt, I tried hardcoding the file name bu ...

Utilizing Node and Socket.io to transmit data periodically via websockets from a CSV file

I am relatively new to working with Node.js and Express.js. My goal is to set up a websocket server that can send CSV data at irregular intervals stored within the file itself, line by line. The structure of the CSV looks something like this: [timeout [ms] ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...

Initiate the node.js server automatically upon Windows 8 startup

Seeking advice on setting up a node.js server to run automatically on startup in Windows. Additionally, I want to launch a standalone application after the server starts. Any recommendations on the most efficient way to achieve this? ...

Javascript - Converting a function to run asynchronously

Just starting to work with Node.js for the first time and feeling a bit puzzled by asynchronous functions. I'm getting better at identifying when async is causing issues, but still unsure how to fix them. Here's the code snippet in question: fu ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

Exploring the functionality of the 'useBodyParser' option in Nestjs

Issue with 'useBodyParser' in Nestjs Application I am encountering an error when trying to utilize the useBodyParser option on my Nestjs application instance. Error: Property 'useBodyParser' is not found on type 'NestExpressAppl ...

Do native node.js addons still require HandleScopes to be used?

The Node.js v6.4.0 documentation on Addons outlines a specific pattern that functions must follow. void X(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); ... } In this version, there is no need to instantiat ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

Can both a Node image and a Python image be run simultaneously within a single Dockerfile?

I am considering putting my logic and backend in python and the frontend in React/Typescript. However, I am unsure if it's feasible to have a single Dockerfile that incorporates both a python image and a node image. Should I pursue this approach or o ...

What steps should I follow to upgrade a Node.js native addon and integrate the latest API changes?

Looking for guidance on updating an old Node.js native addon that no longer works with Node.js 12 and above due to deprecated native APIs. I've fixed most errors, but one issue remains regarding initializing and calling a callback function. The new AP ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

Compiling React Native in Node.JS encountered a critical error

I'm in the process of putting together a react native guide for creating forms, which can be accessed here: - https://github.com/smhatre59/cloudstorage However, when I try to compile using "npm run-script build" or even for development using "npm sta ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...