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

Posted April 19th, 2020 • 1 min read

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

Middleware

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 (req.headers.host.slice(0, 4) === "www.") {
    var newHost = req.headers.host.slice(4);
    return res.redirect(301, req.protocol + "://" + newHost + req.originalUrl);
  }
  next();
}

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

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! 👌

Stay up to date

Want to know when a new post comes out and stay in the loop on tips, tricks and gotchas? Consider signing up for the Mindthecode newsletter.

Comments

Keep reading

April 18th, 2016 • 6 min read
Recently React Storybook came out. It's a tool to isolate your React Components to develop and design them outside of your app. I'll be walking through setting it up
May 22nd, 2011 • 4 min read
The following setup can work nicely when you develop your sites locally and don't want to change the configuration every time you upload it.
September 26th, 2017 • 15 min read
I always wanted to toy around with an image recognition library but it always felt kinda daunting. Today we'll explore this together to detect license plates.