You can create an HTTPS server and pass along a private key and certificate like so:
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
const options = {
key: fs.readFileSync('path/to/key', 'utf8'),
cert: fs.readFileSync('path/to/cert', 'utf8'),
};
const httpsServer = https.createServer(options, app);
httpsServer.listen(8443);
If you don't want to respond to HTTP requests at all, simply don't create an HTTP server. If you want to to forward users to HTTPS instead, you could add something like this:
const http = require('http');
app.use('*', (req, res, next) => {
if (!req.secure) {
const [ host ] = req.headers.host.split(':');
return res.redirect(`https://${host}:8443${req.url}`);
}
return next();
});
const httpServer = http.createServer(app);
httpServer.listen(8000);
Or you can handle this at reverse-proxy level. E.g. for Nginx:
server {
listen 80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
}