Home > Software design >  Is this the rightway to redirect HTTP request to HTTPS in express server?
Is this the rightway to redirect HTTP request to HTTPS in express server?

Time:07-10

I'm currently working on my API and need that work in HTTPS Protocol/SSL so I did this.

https.createServer({
    key: fs.readFileSync(certKeySSLPath),
    cert: fs.readFileSync(certSSLPath)
}, app).listen(serverPORTHTTPS);

console.log('Server listening on PORT: '   serverPORTHTTPS);

And it works completely fine, now the problem is that when I make a petition without specific HTTPS or HTTP protocol the request is not received so I think

Ok, let's create an HTTP server on port 80 and redirect all the traffic to HTTPS technically it works but I'm not sure that is the best practice, someone can tell me if I'm right? Is this a good solution to thinking at the production level?

This is my code

const app = express()

// * Redirecting HTTP Request To HTTPS

app.use((req,res,next) => {


    if(!req.secure){
        res.redirect("https://"   req.headers.host   req.url);
    }

    next()

})

// * Initializing HTTP

app.listen(serverPORTHTTP, (req,res) => {

    console.log('Server listening on PORT: '   serverPORTHTTP);

});

// * Initializing HTTPS - SSL Server

https.createServer({
    key: fs.readFileSync(certKeySSLPath),
    cert: fs.readFileSync(certSSLPath)
}, app).listen(serverPORTHTTPS);

console.log('Server listening on PORT: '   serverPORTHTTPS);

CodePudding user response:

my 5 cents here that you would not handle ssl in backend, you do that in reverse proxy like nginx.

When you run server you start it on port then you reverse proxing that server so your api would be let say localhost:3000 and you would have nginx that would define what server should do when domain is called with http then you would do redirect there to https and then you would redirect to localhost:3000

Guess you should check that blog post out https://blog.logrocket.com/how-to-run-a-node-js-server-with-nginx/

  • Related