Permanent Redirect Non-WWW to WWW in Node.JS on Heroku

For SEO reasons it’s important to make sure that users only visit your site through a single domain name. Either www.example.com or example.com, but not both. In most cases a .htaccess change is the easiest fix. But not when you’re deploying to an environment that doesn’t have Apache, like Heroku. Here’s a quick way to get this functionality using Express on Node.JS

Since you probably only want to do this in a production environment, I suggest you place this in

that configure block.

Before you add any middleware add the following route:

app.get('*', function(req, res, next) {
  if (req.headers.host.slice(0, 3) != 'www') {
    res.redirect('http://www.' + req.headers.host + req.url, 301);
  } else {
    next();
  }
});

That’s really all there is to it. Since most frameworks have similar routing options, you should be able to adapt this to other frameworks, such as Geddy.

BTW I’m planning to launch a Node.JS app in November as part of Hacker News’ Launch an App Month.