How to redirect www traffic to non-www in your Express app

It’s good practice to force either www or non-www for your website. But how do you redirect your traffic properly using Express?


The easiest way to do anything in Express is by using middleware. This way you can process every request and take action if you need to.

function redirectWwwTraffic(req, res, next) {
  if (, 4) === "www.") {
    var newHost =;
    return res.redirect(301, req.protocol + "://" + newHost + req.originalUrl);

app.set("trust proxy", true);

If you place this before starting your express app it will do the following:

For every request it checks if the host starts with www. If it does, it takes the original URL and redirects it to the non-www version with a 301 redirect.

Simple and easy! ๐Ÿ‘Œ