HTTPS redirect for Node Express app on Heroku

HTTPS redirect for Node Express app on Heroku

a redirect middleware

The Express request object has a secure boolean attribute. When secure=true, the request is on https. However, for apps hosted on Heroku, the request.secure will always be false. So, we need a further step to redirect users to https.

Heroku header

Indeed, Heroku forwards an http header that allow us to detect the secure attribute. On Heroku, request.header('x-forwarded-proto') will contain the actual protocol string (i.e., http or https).

Express middleware for HTTPS redirect

If you’re using the Express framework, then you can use the app.use() functionality to specify a middleware. Since Heroku already implemented HTTPS in the production environment, we can use the process.env.NODE_ENV to check for prod:

if (process.env.NODE_ENV === 'production') {
    app.use((req, res, next) => {
        if (req.header('x-forwarded-proto') !== 'https') {
            res.redirect(`https://${req.header('host')}${req.url}`)
        } else {
            next()
        }
    })
}

This middleware could be more selective per route if you wanted. And you could even enhance the middleware to use inspect both the http header and the Express secure flag.

Ads by Google

林宏

Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.4 billion 🇨🇳. This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.

YOU MAY ALSO LIKE

Using Liquid in Jekyll - Live with Demos

Web Notes

2016.08.20

Using Liquid in Jekyll - Live with Demos

Liquid is a simple templating language that Jekyll uses to process pages on your site. With Liquid you can output an modify variables, have logic statements inside your pages and loop over content.

HTML 相对路径和绝对路径区别分析

Web Notes

2015.09.26

HTML 相对路径和绝对路径区别分析

HTML 初学者会经常遇到这样一个问题,如何正确引用一个文件。比如,怎样在一个 HTML 网页中引用另外一个 HTML 网页作为超链接(hyperlink),怎样在一个网页中插入一张图片。如果你在引用文件时(如加入超链接,或者插入图片等),使用了错误的文件路径,就会导致引用失效(无法浏览链接文件,或无法显示插入的图片等)。

Understanding Nginx location directive

Tools

2020.09.12

Understanding Nginx location directive

Nginx location directives are essential when working with Nginx. They can be located within server blocks or other location blocks. Understanding how location directives are used to process the URI of client request can help make the request handling seem less unpredictable.